Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGBlocks.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
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 blocks.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGBlocks.h"
14
#include "CGCXXABI.h"
15
#include "CGDebugInfo.h"
16
#include "CGObjCRuntime.h"
17
#include "CGOpenCLRuntime.h"
18
#include "CodeGenFunction.h"
19
#include "CodeGenModule.h"
20
#include "ConstantEmitter.h"
21
#include "TargetInfo.h"
22
#include "clang/AST/Attr.h"
23
#include "clang/AST/DeclObjC.h"
24
#include "clang/CodeGen/ConstantInitBuilder.h"
25
#include "llvm/ADT/SmallSet.h"
26
#include "llvm/IR/DataLayout.h"
27
#include "llvm/IR/Module.h"
28
#include "llvm/Support/ScopedPrinter.h"
29
#include <algorithm>
30
#include <cstdio>
31
32
using namespace clang;
33
using namespace CodeGen;
34
35
CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
36
  : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37
    HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
38
    CapturesNonExternalType(false), LocalAddress(Address::invalid()),
39
1.04k
    StructureType(nullptr), Block(block) {
40
41
  // Skip asm prefix, if any.  'name' is usually taken directly from
42
  // the mangled name of the enclosing function.
43
1.04k
  if (!name.empty() && name[0] == '\01')
44
35
    name = name.substr(1);
45
1.04k
}
46
47
// Anchor the vtable to this translation unit.
48
80
BlockByrefHelpers::~BlockByrefHelpers() {}
49
50
/// Build the given block as a global block.
51
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
52
                                        const CGBlockInfo &blockInfo,
53
                                        llvm::Constant *blockFn);
54
55
/// Build the helper function to copy a block.
56
static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
57
365
                                       const CGBlockInfo &blockInfo) {
58
365
  return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
59
365
}
60
61
/// Build the helper function to dispose of a block.
62
static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
63
365
                                          const CGBlockInfo &blockInfo) {
64
365
  return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
65
365
}
66
67
namespace {
68
69
/// Represents a type of copy/destroy operation that should be performed for an
70
/// entity that's captured by a block.
71
enum class BlockCaptureEntityKind {
72
  CXXRecord, // Copy or destroy
73
  ARCWeak,
74
  ARCStrong,
75
  NonTrivialCStruct,
76
  BlockObject, // Assign or release
77
  None
78
};
79
80
/// Represents a captured entity that requires extra operations in order for
81
/// this entity to be copied or destroyed correctly.
82
struct BlockCaptureManagedEntity {
83
  BlockCaptureEntityKind CopyKind, DisposeKind;
84
  BlockFieldFlags CopyFlags, DisposeFlags;
85
  const BlockDecl::Capture *CI;
86
  const CGBlockInfo::Capture *Capture;
87
88
  BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
89
                            BlockCaptureEntityKind DisposeType,
90
                            BlockFieldFlags CopyFlags,
91
                            BlockFieldFlags DisposeFlags,
92
                            const BlockDecl::Capture &CI,
93
                            const CGBlockInfo::Capture &Capture)
94
      : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
95
1.78k
        DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
96
97
1.72k
  bool operator<(const BlockCaptureManagedEntity &Other) const {
98
1.72k
    return Capture->getOffset() < Other.Capture->getOffset();
99
1.72k
  }
100
};
101
102
enum class CaptureStrKind {
103
  // String for the copy helper.
104
  CopyHelper,
105
  // String for the dispose helper.
106
  DisposeHelper,
107
  // Merge the strings for the copy helper and dispose helper.
108
  Merged
109
};
110
111
} // end anonymous namespace
112
113
static void findBlockCapturedManagedEntities(
114
    const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
115
    SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
116
117
static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
118
                                      CaptureStrKind StrKind,
119
                                      CharUnits BlockAlignment,
120
                                      CodeGenModule &CGM);
121
122
static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
123
367
                                          CodeGenModule &CGM) {
124
367
  std::string Name = "__block_descriptor_";
125
367
  Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
126
127
367
  if (BlockInfo.needsCopyDisposeHelpers()) {
128
240
    if (CGM.getLangOpts().Exceptions)
129
59
      Name += "e";
130
240
    if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
131
29
      Name += "a";
132
240
    Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
133
134
240
    SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
135
240
    findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
136
240
                                     ManagedCaptures);
137
138
486
    for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
139
486
      Name += llvm::to_string(E.Capture->getOffset().getQuantity());
140
141
486
      if (E.CopyKind == E.DisposeKind) {
142
        // If CopyKind and DisposeKind are the same, merge the capture
143
        // information.
144
466
        assert(E.CopyKind != BlockCaptureEntityKind::None &&
145
466
               "shouldn't see BlockCaptureManagedEntity that is None");
146
466
        Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
147
466
                                   BlockInfo.BlockAlign, CGM);
148
20
      } else {
149
        // If CopyKind and DisposeKind are not the same, which can happen when
150
        // either Kind is None or the captured object is a __strong block,
151
        // concatenate the copy and dispose strings.
152
20
        Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
153
20
                                   BlockInfo.BlockAlign, CGM);
154
20
        Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
155
20
                                   BlockInfo.BlockAlign, CGM);
156
20
      }
157
486
    }
158
240
    Name += "_";
159
240
  }
160
161
367
  std::string TypeAtEncoding =
162
367
      CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
163
  /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
164
  /// a separator between symbol name and symbol version.
165
367
  std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
166
367
  Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
167
367
  Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
168
367
  return Name;
169
367
}
170
171
/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
172
/// buildBlockDescriptor is accessed from 5th field of the Block_literal
173
/// meta-data and contains stationary information about the block literal.
174
/// Its definition will have 4 (or optionally 6) words.
175
/// \code
176
/// struct Block_descriptor {
177
///   unsigned long reserved;
178
///   unsigned long size;  // size of Block_literal metadata in bytes.
179
///   void *copy_func_helper_decl;  // optional copy helper.
180
///   void *destroy_func_decl; // optional destructor helper.
181
///   void *block_method_encoding_address; // @encode for block literal signature.
182
///   void *block_layout_info; // encoding of captured block variables.
183
/// };
184
/// \endcode
185
static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
186
975
                                            const CGBlockInfo &blockInfo) {
187
975
  ASTContext &C = CGM.getContext();
188
189
975
  llvm::IntegerType *ulong =
190
975
    cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
191
975
  llvm::PointerType *i8p = nullptr;
192
975
  if (CGM.getLangOpts().OpenCL)
193
0
    i8p =
194
0
      llvm::Type::getInt8PtrTy(
195
0
           CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
196
975
  else
197
975
    i8p = CGM.VoidPtrTy;
198
199
975
  std::string descName;
200
201
  // If an equivalent block descriptor global variable exists, return it.
202
975
  if (C.getLangOpts().ObjC &&
203
400
      CGM.getLangOpts().getGC() == LangOptions::NonGC) {
204
367
    descName = getBlockDescriptorName(blockInfo, CGM);
205
367
    if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
206
106
      return llvm::ConstantExpr::getBitCast(desc,
207
106
                                            CGM.getBlockDescriptorType());
208
869
  }
209
210
  // If there isn't an equivalent block descriptor global variable, create a new
211
  // one.
212
869
  ConstantInitBuilder builder(CGM);
213
869
  auto elements = builder.beginStruct();
214
215
  // reserved
216
869
  elements.addInt(ulong, 0);
217
218
  // Size
219
  // FIXME: What is the right way to say this doesn't fit?  We should give
220
  // a user diagnostic in that case.  Better fix would be to change the
221
  // API to size_t.
222
869
  elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
223
224
  // Optional copy/dispose helpers.
225
869
  bool hasInternalHelper = false;
226
869
  if (blockInfo.needsCopyDisposeHelpers()) {
227
    // copy_func_helper_decl
228
365
    llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
229
365
    elements.add(copyHelper);
230
231
    // destroy_func_decl
232
365
    llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
233
365
    elements.add(disposeHelper);
234
235
365
    if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
236
353
        cast<llvm::Function>(disposeHelper->getOperand(0))
237
353
            ->hasInternalLinkage())
238
14
      hasInternalHelper = true;
239
365
  }
240
241
  // Signature.  Mandatory ObjC-style method descriptor @encode sequence.
242
869
  std::string typeAtEncoding =
243
869
    CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
244
869
  elements.add(llvm::ConstantExpr::getBitCast(
245
869
    CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
246
247
  // GC layout.
248
869
  if (C.getLangOpts().ObjC) {
249
294
    if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
250
33
      elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
251
261
    else
252
261
      elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
253
294
  }
254
575
  else
255
575
    elements.addNullPointer(i8p);
256
257
869
  unsigned AddrSpace = 0;
258
869
  if (C.getLangOpts().OpenCL)
259
0
    AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
260
261
869
  llvm::GlobalValue::LinkageTypes linkage;
262
869
  if (descName.empty()) {
263
608
    linkage = llvm::GlobalValue::InternalLinkage;
264
608
    descName = "__block_descriptor_tmp";
265
261
  } else if (hasInternalHelper) {
266
    // If either the copy helper or the dispose helper has internal linkage,
267
    // the block descriptor must have internal linkage too.
268
13
    linkage = llvm::GlobalValue::InternalLinkage;
269
248
  } else {
270
248
    linkage = llvm::GlobalValue::LinkOnceODRLinkage;
271
248
  }
272
273
869
  llvm::GlobalVariable *global =
274
869
      elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
275
869
                                     /*constant*/ true, linkage, AddrSpace);
276
277
869
  if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
278
248
    if (CGM.supportsCOMDAT())
279
4
      global->setComdat(CGM.getModule().getOrInsertComdat(descName));
280
248
    global->setVisibility(llvm::GlobalValue::HiddenVisibility);
281
248
    global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
282
248
  }
283
284
869
  return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
285
869
}
286
287
/*
288
  Purely notional variadic template describing the layout of a block.
289
290
  template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
291
  struct Block_literal {
292
    /// Initialized to one of:
293
    ///   extern void *_NSConcreteStackBlock[];
294
    ///   extern void *_NSConcreteGlobalBlock[];
295
    ///
296
    /// In theory, we could start one off malloc'ed by setting
297
    /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
298
    /// this isa:
299
    ///   extern void *_NSConcreteMallocBlock[];
300
    struct objc_class *isa;
301
302
    /// These are the flags (with corresponding bit number) that the
303
    /// compiler is actually supposed to know about.
304
    ///  23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
305
    ///  25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
306
    ///   descriptor provides copy and dispose helper functions
307
    ///  26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
308
    ///   object with a nontrivial destructor or copy constructor
309
    ///  28. BLOCK_IS_GLOBAL - indicates that the block is allocated
310
    ///   as global memory
311
    ///  29. BLOCK_USE_STRET - indicates that the block function
312
    ///   uses stret, which objc_msgSend needs to know about
313
    ///  30. BLOCK_HAS_SIGNATURE - indicates that the block has an
314
    ///   @encoded signature string
315
    /// And we're not supposed to manipulate these:
316
    ///  24. BLOCK_NEEDS_FREE - indicates that the block has been moved
317
    ///   to malloc'ed memory
318
    ///  27. BLOCK_IS_GC - indicates that the block has been moved to
319
    ///   to GC-allocated memory
320
    /// Additionally, the bottom 16 bits are a reference count which
321
    /// should be zero on the stack.
322
    int flags;
323
324
    /// Reserved;  should be zero-initialized.
325
    int reserved;
326
327
    /// Function pointer generated from block literal.
328
    _ResultType (*invoke)(Block_literal *, _ParamTypes...);
329
330
    /// Block description metadata generated from block literal.
331
    struct Block_descriptor *block_descriptor;
332
333
    /// Captured values follow.
334
    _CapturesTypes captures...;
335
  };
336
 */
337
338
namespace {
339
  /// A chunk of data that we actually have to capture in the block.
340
  struct BlockLayoutChunk {
341
    CharUnits Alignment;
342
    CharUnits Size;
343
    Qualifiers::ObjCLifetime Lifetime;
344
    const BlockDecl::Capture *Capture; // null for 'this'
345
    llvm::Type *Type;
346
    QualType FieldType;
347
348
    BlockLayoutChunk(CharUnits align, CharUnits size,
349
                     Qualifiers::ObjCLifetime lifetime,
350
                     const BlockDecl::Capture *capture,
351
                     llvm::Type *type, QualType fieldType)
352
      : Alignment(align), Size(size), Lifetime(lifetime),
353
2.25k
        Capture(capture), Type(type), FieldType(fieldType) {}
354
355
    /// Tell the block info that this chunk has the given field index.
356
2.26k
    void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
357
2.26k
      if (!Capture) {
358
27
        info.CXXThisIndex = index;
359
27
        info.CXXThisOffset = offset;
360
2.23k
      } else {
361
2.23k
        auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
362
2.23k
        info.Captures.insert({Capture->getVariable(), C});
363
2.23k
      }
364
2.26k
    }
365
  };
366
367
  /// Order by 1) all __strong together 2) next, all byfref together 3) next,
368
  /// all __weak together. Preserve descending alignment in all situations.
369
3.02k
  bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
370
3.02k
    if (left.Alignment != right.Alignment)
371
1.58k
      return left.Alignment > right.Alignment;
372
373
2.88k
    
auto getPrefOrder = [](const BlockLayoutChunk &chunk) 1.44k
{
374
2.88k
      if (chunk.Capture && 
chunk.Capture->isByRef()2.86k
)
375
214
        return 1;
376
2.66k
      if (chunk.Lifetime == Qualifiers::OCL_Strong)
377
172
        return 0;
378
2.49k
      if (chunk.Lifetime == Qualifiers::OCL_Weak)
379
260
        return 2;
380
2.23k
      return 3;
381
2.23k
    };
382
383
1.44k
    return getPrefOrder(left) < getPrefOrder(right);
384
1.44k
  }
385
} // end anonymous namespace
386
387
/// Determines if the given type is safe for constant capture in C++.
388
25
static bool isSafeForCXXConstantCapture(QualType type) {
389
25
  const RecordType *recordType =
390
25
    type->getBaseElementTypeUnsafe()->getAs<RecordType>();
391
392
  // Only records can be unsafe.
393
25
  if (!recordType) 
return true9
;
394
395
16
  const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
396
397
  // Maintain semantics for classes with non-trivial dtors or copy ctors.
398
16
  if (!record->hasTrivialDestructor()) 
return false2
;
399
14
  if (record->hasNonTrivialCopyConstructor()) 
return false4
;
400
401
  // Otherwise, we just have to make sure there aren't any mutable
402
  // fields that might have changed since initialization.
403
10
  return !record->hasMutableFields();
404
10
}
405
406
/// It is illegal to modify a const object after initialization.
407
/// Therefore, if a const object has a constant initializer, we don't
408
/// actually need to keep storage for it in the block; we'll just
409
/// rematerialize it at the start of the block function.  This is
410
/// acceptable because we make no promises about address stability of
411
/// captured variables.
412
static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
413
                                            CodeGenFunction *CGF,
414
1.97k
                                            const VarDecl *var) {
415
  // Return if this is a function parameter. We shouldn't try to
416
  // rematerialize default arguments of function parameters.
417
1.97k
  if (isa<ParmVarDecl>(var))
418
156
    return nullptr;
419
420
1.82k
  QualType type = var->getType();
421
422
  // We can only do this if the variable is const.
423
1.82k
  if (!type.isConstQualified()) 
return nullptr1.75k
;
424
425
  // Furthermore, in C++ we have to worry about mutable fields:
426
  // C++ [dcl.type.cv]p4:
427
  //   Except that any class member declared mutable can be
428
  //   modified, any attempt to modify a const object during its
429
  //   lifetime results in undefined behavior.
430
64
  if (CGM.getLangOpts().CPlusPlus && 
!isSafeForCXXConstantCapture(type)25
)
431
7
    return nullptr;
432
433
  // If the variable doesn't have any initializer (shouldn't this be
434
  // invalid?), it's not clear what we should do.  Maybe capture as
435
  // zero?
436
57
  const Expr *init = var->getInit();
437
57
  if (!init) 
return nullptr17
;
438
439
40
  return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
440
40
}
441
442
/// Get the low bit of a nonzero character count.  This is the
443
/// alignment of the nth byte if the 0th byte is universally aligned.
444
4.37k
static CharUnits getLowBit(CharUnits v) {
445
4.37k
  return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
446
4.37k
}
447
448
static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
449
1.04k
                             SmallVectorImpl<llvm::Type*> &elementTypes) {
450
451
1.04k
  assert(elementTypes.empty());
452
1.04k
  if (CGM.getLangOpts().OpenCL) {
453
    // The header is basically 'struct { int; int; generic void *;
454
    // custom_fields; }'. Assert that struct is packed.
455
72
    auto GenericAS =
456
72
        CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
457
72
    auto GenPtrAlign =
458
72
        CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
459
72
    auto GenPtrSize =
460
72
        CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
461
72
    assert(CGM.getIntSize() <= GenPtrSize);
462
72
    assert(CGM.getIntAlign() <= GenPtrAlign);
463
72
    assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
464
72
    elementTypes.push_back(CGM.IntTy); /* total size */
465
72
    elementTypes.push_back(CGM.IntTy); /* align */
466
72
    elementTypes.push_back(
467
72
        CGM.getOpenCLRuntime()
468
72
            .getGenericVoidPointerType()); /* invoke function */
469
72
    unsigned Offset =
470
72
        2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
471
72
    unsigned BlockAlign = GenPtrAlign.getQuantity();
472
72
    if (auto *Helper =
473
0
            CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
474
0
      for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
475
        // TargetOpenCLBlockHelp needs to make sure the struct is packed.
476
        // If necessary, add padding fields to the custom fields.
477
0
        unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
478
0
        if (BlockAlign < Align)
479
0
          BlockAlign = Align;
480
0
        assert(Offset % Align == 0);
481
0
        Offset += CGM.getDataLayout().getTypeAllocSize(I);
482
0
        elementTypes.push_back(I);
483
0
      }
484
0
    }
485
72
    info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
486
72
    info.BlockSize = CharUnits::fromQuantity(Offset);
487
975
  } else {
488
    // The header is basically 'struct { void *; int; int; void *; void *; }'.
489
    // Assert that the struct is packed.
490
975
    assert(CGM.getIntSize() <= CGM.getPointerSize());
491
975
    assert(CGM.getIntAlign() <= CGM.getPointerAlign());
492
975
    assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
493
975
    info.BlockAlign = CGM.getPointerAlign();
494
975
    info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
495
975
    elementTypes.push_back(CGM.VoidPtrTy);
496
975
    elementTypes.push_back(CGM.IntTy);
497
975
    elementTypes.push_back(CGM.IntTy);
498
975
    elementTypes.push_back(CGM.VoidPtrTy);
499
975
    elementTypes.push_back(CGM.getBlockDescriptorType());
500
975
  }
501
1.04k
}
502
503
static QualType getCaptureFieldType(const CodeGenFunction &CGF,
504
2.23k
                                    const BlockDecl::Capture &CI) {
505
2.23k
  const VarDecl *VD = CI.getVariable();
506
507
  // If the variable is captured by an enclosing block or lambda expression,
508
  // use the type of the capture field.
509
2.23k
  if (CGF.BlockInfo && 
CI.isNested()18
)
510
10
    return CGF.BlockInfo->getCapture(VD).fieldType();
511
2.22k
  if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
512
16
    return FD->getType();
513
  // If the captured variable is a non-escaping __block variable, the field
514
  // type is the reference type. If the variable is a __block variable that
515
  // already has a reference type, the field type is the variable's type.
516
2.20k
  return VD->isNonEscapingByref() ?
517
2.20k
         
CGF.getContext().getLValueReferenceType(VD->getType())4
: VD->getType();
518
2.20k
}
519
520
/// Compute the layout of the given block.  Attempts to lay the block
521
/// out with minimal space requirements.
522
static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
523
1.04k
                             CGBlockInfo &info) {
524
1.04k
  ASTContext &C = CGM.getContext();
525
1.04k
  const BlockDecl *block = info.getBlockDecl();
526
527
1.04k
  SmallVector<llvm::Type*, 8> elementTypes;
528
1.04k
  initializeForBlockHeader(CGM, info, elementTypes);
529
1.04k
  bool hasNonConstantCustomFields = false;
530
1.04k
  if (auto *OpenCLHelper =
531
0
          CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
532
0
    hasNonConstantCustomFields =
533
0
        !OpenCLHelper->areAllCustomFieldValuesConstant(info);
534
1.04k
  if (!block->hasCaptures() && 
!hasNonConstantCustomFields345
) {
535
345
    info.StructureType =
536
345
      llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
537
345
    info.CanBeGlobal = true;
538
345
    return;
539
345
  }
540
702
  else if (C.getLangOpts().ObjC &&
541
345
           CGM.getLangOpts().getGC() == LangOptions::NonGC)
542
316
    info.HasCapturedVariableLayout = true;
543
544
  // Collect the layout chunks.
545
702
  SmallVector<BlockLayoutChunk, 16> layout;
546
702
  layout.reserve(block->capturesCXXThis() +
547
702
                 (block->capture_end() - block->capture_begin()));
548
549
702
  CharUnits maxFieldAlign;
550
551
  // First, 'this'.
552
702
  if (block->capturesCXXThis()) {
553
27
    assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
554
27
           "Can't capture 'this' outside a method");
555
27
    QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
556
557
    // Theoretically, this could be in a different address space, so
558
    // don't assume standard pointer size/align.
559
27
    llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
560
27
    std::pair<CharUnits,CharUnits> tinfo
561
27
      = CGM.getContext().getTypeInfoInChars(thisType);
562
27
    maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
563
564
27
    layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
565
27
                                      Qualifiers::OCL_None,
566
27
                                      nullptr, llvmType, thisType));
567
27
  }
568
569
  // Next, all the block captures.
570
2.23k
  for (const auto &CI : block->captures()) {
571
2.23k
    const VarDecl *variable = CI.getVariable();
572
573
2.23k
    if (CI.isEscapingByref()) {
574
      // We have to copy/dispose of the __block reference.
575
260
      info.NeedsCopyDispose = true;
576
577
      // Just use void* instead of a pointer to the byref type.
578
260
      CharUnits align = CGM.getPointerAlign();
579
260
      maxFieldAlign = std::max(maxFieldAlign, align);
580
581
      // Since a __block variable cannot be captured by lambdas, its type and
582
      // the capture field type should always match.
583
260
      assert(CGF && getCaptureFieldType(*CGF, CI) == variable->getType() &&
584
260
             "capture type differs from the variable type");
585
260
      layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
586
260
                                        Qualifiers::OCL_None, &CI,
587
260
                                        CGM.VoidPtrTy, variable->getType()));
588
260
      continue;
589
260
    }
590
591
    // Otherwise, build a layout chunk with the size and alignment of
592
    // the declaration.
593
1.97k
    if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
594
5
      info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
595
5
      continue;
596
5
    }
597
598
1.97k
    QualType VT = getCaptureFieldType(*CGF, CI);
599
600
    // If we have a lifetime qualifier, honor it for capture purposes.
601
    // That includes *not* copying it if it's __unsafe_unretained.
602
1.97k
    Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
603
1.97k
    if (lifetime) {
604
300
      switch (lifetime) {
605
0
      case Qualifiers::OCL_None: llvm_unreachable("impossible");
606
4
      case Qualifiers::OCL_ExplicitNone:
607
4
      case Qualifiers::OCL_Autoreleasing:
608
4
        break;
609
610
296
      case Qualifiers::OCL_Strong:
611
296
      case Qualifiers::OCL_Weak:
612
296
        info.NeedsCopyDispose = true;
613
300
      }
614
615
    // Block pointers require copy/dispose.  So do Objective-C pointers.
616
1.67k
    } else if (VT->isObjCRetainableType()) {
617
      // But honor the inert __unsafe_unretained qualifier, which doesn't
618
      // actually make it into the type system.
619
82
       if (VT->isObjCInertUnsafeUnretainedType()) {
620
10
        lifetime = Qualifiers::OCL_ExplicitNone;
621
72
      } else {
622
72
        info.NeedsCopyDispose = true;
623
        // used for mrr below.
624
72
        lifetime = Qualifiers::OCL_Strong;
625
72
      }
626
627
    // So do types that require non-trivial copy construction.
628
1.59k
    } else if (CI.hasCopyExpr()) {
629
29
      info.NeedsCopyDispose = true;
630
29
      info.HasCXXObject = true;
631
29
      if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
632
12
        info.CapturesNonExternalType = true;
633
634
    // So do C structs that require non-trivial copy construction or
635
    // destruction.
636
1.56k
    } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
637
1.55k
               VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
638
2
      info.NeedsCopyDispose = true;
639
640
    // And so do types with destructors.
641
1.55k
    } else if (CGM.getLangOpts().CPlusPlus) {
642
1.40k
      if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
643
289
        if (!record->hasTrivialDestructor()) {
644
73
          info.HasCXXObject = true;
645
73
          info.NeedsCopyDispose = true;
646
73
          if (!record->isExternallyVisible())
647
0
            info.CapturesNonExternalType = true;
648
73
        }
649
289
      }
650
1.40k
    }
651
652
1.97k
    CharUnits size = C.getTypeSizeInChars(VT);
653
1.97k
    CharUnits align = C.getDeclAlign(variable);
654
655
1.97k
    maxFieldAlign = std::max(maxFieldAlign, align);
656
657
1.97k
    llvm::Type *llvmType =
658
1.97k
      CGM.getTypes().ConvertTypeForMem(VT);
659
660
1.97k
    layout.push_back(
661
1.97k
        BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
662
1.97k
  }
663
664
  // If that was everything, we're done here.
665
702
  if (layout.empty()) {
666
4
    info.StructureType =
667
4
      llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
668
4
    info.CanBeGlobal = true;
669
4
    return;
670
4
  }
671
672
  // Sort the layout by alignment.  We have to use a stable sort here
673
  // to get reproducible results.  There should probably be an
674
  // llvm::array_pod_stable_sort.
675
698
  llvm::stable_sort(layout);
676
677
  // Needed for blocks layout info.
678
698
  info.BlockHeaderForcedGapOffset = info.BlockSize;
679
698
  info.BlockHeaderForcedGapSize = CharUnits::Zero();
680
681
698
  CharUnits &blockSize = info.BlockSize;
682
698
  info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
683
684
  // Assuming that the first byte in the header is maximally aligned,
685
  // get the alignment of the first byte following the header.
686
698
  CharUnits endAlign = getLowBit(blockSize);
687
688
  // If the end of the header isn't satisfactorily aligned for the
689
  // maximum thing, look for things that are okay with the header-end
690
  // alignment, and keep appending them until we get something that's
691
  // aligned right.  This algorithm is only guaranteed optimal if
692
  // that condition is satisfied at some point; otherwise we can get
693
  // things like:
694
  //   header                 // next byte has alignment 4
695
  //   something_with_size_5; // next byte has alignment 1
696
  //   something_with_alignment_8;
697
  // which has 7 bytes of padding, as opposed to the naive solution
698
  // which might have less (?).
699
698
  if (endAlign < maxFieldAlign) {
700
19
    SmallVectorImpl<BlockLayoutChunk>::iterator
701
19
      li = layout.begin() + 1, le = layout.end();
702
703
    // Look for something that the header end is already
704
    // satisfactorily aligned for.
705
19
    for (; li != le && 
endAlign < li->Alignment15
;
++li0
)
706
0
      ;
707
708
    // If we found something that's naturally aligned for the end of
709
    // the header, keep adding things...
710
19
    if (li != le) {
711
15
      SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
712
30
      for (; li != le; 
++li15
) {
713
19
        assert(endAlign >= li->Alignment);
714
715
19
        li->setIndex(info, elementTypes.size(), blockSize);
716
19
        elementTypes.push_back(li->Type);
717
19
        blockSize += li->Size;
718
19
        endAlign = getLowBit(blockSize);
719
720
        // ...until we get to the alignment of the maximum field.
721
19
        if (endAlign >= maxFieldAlign) {
722
4
          break;
723
4
        }
724
19
      }
725
      // Don't re-append everything we just appended.
726
15
      layout.erase(first, li);
727
15
    }
728
19
  }
729
730
698
  assert(endAlign == getLowBit(blockSize));
731
732
  // At this point, we just have to add padding if the end align still
733
  // isn't aligned right.
734
698
  if (endAlign < maxFieldAlign) {
735
15
    CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
736
15
    CharUnits padding = newBlockSize - blockSize;
737
738
    // If we haven't yet added any fields, remember that there was an
739
    // initial gap; this need to go into the block layout bit map.
740
15
    if (blockSize == info.BlockHeaderForcedGapOffset) {
741
4
      info.BlockHeaderForcedGapSize = padding;
742
4
    }
743
744
15
    elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
745
15
                                                padding.getQuantity()));
746
15
    blockSize = newBlockSize;
747
15
    endAlign = getLowBit(blockSize); // might be > maxFieldAlign
748
15
  }
749
750
698
  assert(endAlign >= maxFieldAlign);
751
698
  assert(endAlign == getLowBit(blockSize));
752
  // Slam everything else on now.  This works because they have
753
  // strictly decreasing alignment and we expect that size is always a
754
  // multiple of alignment.
755
698
  for (SmallVectorImpl<BlockLayoutChunk>::iterator
756
2.94k
         li = layout.begin(), le = layout.end(); li != le; 
++li2.24k
) {
757
2.24k
    if (endAlign < li->Alignment) {
758
      // size may not be multiple of alignment. This can only happen with
759
      // an over-aligned variable. We will be adding a padding field to
760
      // make the size be multiple of alignment.
761
1
      CharUnits padding = li->Alignment - endAlign;
762
1
      elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
763
1
                                                  padding.getQuantity()));
764
1
      blockSize += padding;
765
1
      endAlign = getLowBit(blockSize);
766
1
    }
767
2.24k
    assert(endAlign >= li->Alignment);
768
2.24k
    li->setIndex(info, elementTypes.size(), blockSize);
769
2.24k
    elementTypes.push_back(li->Type);
770
2.24k
    blockSize += li->Size;
771
2.24k
    endAlign = getLowBit(blockSize);
772
2.24k
  }
773
774
698
  info.StructureType =
775
698
    llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
776
698
}
777
778
/// Emit a block literal expression in the current function.
779
1.00k
llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
780
  // If the block has no captures, we won't have a pre-computed
781
  // layout for it.
782
1.00k
  if (!blockExpr->getBlockDecl()->hasCaptures())
783
    // The block literal is emitted as a global variable, and the block invoke
784
    // function has to be extracted from its initializer.
785
301
    if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
786
2
      return Block;
787
788
1.00k
  CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
789
1.00k
  computeBlockInfo(CGM, this, blockInfo);
790
1.00k
  blockInfo.BlockExpression = blockExpr;
791
1.00k
  if (!blockInfo.CanBeGlobal)
792
698
    blockInfo.LocalAddress = CreateTempAlloca(blockInfo.StructureType,
793
698
                                              blockInfo.BlockAlign, "block");
794
1.00k
  return EmitBlockLiteral(blockInfo);
795
1.00k
}
796
797
1.00k
llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
798
1.00k
  bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
799
1.00k
  auto GenVoidPtrTy =
800
936
      IsOpenCL ? 
CGM.getOpenCLRuntime().getGenericVoidPointerType()65
: VoidPtrTy;
801
936
  LangAS GenVoidPtrAddr = IsOpenCL ? 
LangAS::opencl_generic65
: LangAS::Default;
802
1.00k
  auto GenVoidPtrSize = CharUnits::fromQuantity(
803
1.00k
      CGM.getTarget().getPointerWidth(
804
1.00k
          CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
805
1.00k
      8);
806
  // Using the computed layout, generate the actual block function.
807
1.00k
  bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
808
1.00k
  CodeGenFunction BlockCGF{CGM, true};
809
1.00k
  BlockCGF.SanOpts = SanOpts;
810
1.00k
  auto *InvokeFn = BlockCGF.GenerateBlockFunction(
811
1.00k
      CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
812
1.00k
  auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
813
814
  // If there is nothing to capture, we can emit this as a global block.
815
1.00k
  if (blockInfo.CanBeGlobal)
816
303
    return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
817
818
  // Otherwise, we have to emit this as a local block.
819
820
698
  Address blockAddr = blockInfo.LocalAddress;
821
698
  assert(blockAddr.isValid() && "block has no address!");
822
823
698
  llvm::Constant *isa;
824
698
  llvm::Constant *descriptor;
825
698
  BlockFlags flags;
826
698
  if (!IsOpenCL) {
827
    // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
828
    // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
829
    // block just returns the original block and releasing it is a no-op.
830
680
    llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
831
11
                                   ? CGM.getNSConcreteGlobalBlock()
832
669
                                   : CGM.getNSConcreteStackBlock();
833
680
    isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
834
835
    // Build the block descriptor.
836
680
    descriptor = buildBlockDescriptor(CGM, blockInfo);
837
838
    // Compute the initial on-stack block flags.
839
680
    flags = BLOCK_HAS_SIGNATURE;
840
680
    if (blockInfo.HasCapturedVariableLayout)
841
316
      flags |= BLOCK_HAS_EXTENDED_LAYOUT;
842
680
    if (blockInfo.needsCopyDisposeHelpers())
843
441
      flags |= BLOCK_HAS_COPY_DISPOSE;
844
680
    if (blockInfo.HasCXXObject)
845
98
      flags |= BLOCK_HAS_CXX_OBJ;
846
680
    if (blockInfo.UsesStret)
847
2
      flags |= BLOCK_USE_STRET;
848
680
    if (blockInfo.getBlockDecl()->doesNotEscape())
849
11
      flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
850
680
  }
851
852
5.71k
  auto projectField = [&](unsigned index, const Twine &name) -> Address {
853
5.71k
    return Builder.CreateStructGEP(blockAddr, index, name);
854
5.71k
  };
855
3.45k
  auto storeField = [&](llvm::Value *value, unsigned index, const Twine &name) {
856
3.45k
    Builder.CreateStore(value, projectField(index, name));
857
3.45k
  };
858
859
  // Initialize the block header.
860
698
  {
861
    // We assume all the header fields are densely packed.
862
698
    unsigned index = 0;
863
698
    CharUnits offset;
864
698
    auto addHeaderField = [&](llvm::Value *value, CharUnits size,
865
3.45k
                              const Twine &name) {
866
3.45k
      storeField(value, index, name);
867
3.45k
      offset += size;
868
3.45k
      index++;
869
3.45k
    };
870
871
698
    if (!IsOpenCL) {
872
680
      addHeaderField(isa, getPointerSize(), "block.isa");
873
680
      addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
874
680
                     getIntSize(), "block.flags");
875
680
      addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
876
680
                     "block.reserved");
877
18
    } else {
878
18
      addHeaderField(
879
18
          llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
880
18
          getIntSize(), "block.size");
881
18
      addHeaderField(
882
18
          llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
883
18
          getIntSize(), "block.align");
884
18
    }
885
698
    addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
886
698
    if (!IsOpenCL)
887
680
      addHeaderField(descriptor, getPointerSize(), "block.descriptor");
888
18
    else if (auto *Helper =
889
0
                 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
890
0
      for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
891
0
        addHeaderField(
892
0
            I.first,
893
0
            CharUnits::fromQuantity(
894
0
                CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
895
0
            I.second);
896
0
      }
897
0
    }
898
698
  }
899
900
  // Finally, capture all the values into the block.
901
698
  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
902
903
  // First, 'this'.
904
698
  if (blockDecl->capturesCXXThis()) {
905
27
    Address addr =
906
27
        projectField(blockInfo.CXXThisIndex, "block.captured-this.addr");
907
27
    Builder.CreateStore(LoadCXXThis(), addr);
908
27
  }
909
910
  // Next, captured variables.
911
2.23k
  for (const auto &CI : blockDecl->captures()) {
912
2.23k
    const VarDecl *variable = CI.getVariable();
913
2.23k
    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
914
915
    // Ignore constant captures.
916
2.23k
    if (capture.isConstant()) 
continue1
;
917
918
2.23k
    QualType type = capture.fieldType();
919
920
    // This will be a [[type]]*, except that a byref entry will just be
921
    // an i8**.
922
2.23k
    Address blockField = projectField(capture.getIndex(), "block.captured");
923
924
    // Compute the address of the thing we're going to move into the
925
    // block literal.
926
2.23k
    Address src = Address::invalid();
927
928
2.23k
    if (blockDecl->isConversionFromLambda()) {
929
      // The lambda capture in a lambda's conversion-to-block-pointer is
930
      // special; we'll simply emit it directly.
931
13
      src = Address::invalid();
932
2.21k
    } else if (CI.isEscapingByref()) {
933
260
      if (BlockInfo && 
CI.isNested()7
) {
934
        // We need to use the capture from the enclosing block.
935
3
        const CGBlockInfo::Capture &enclosingCapture =
936
3
            BlockInfo->getCapture(variable);
937
938
        // This is a [[type]]*, except that a byref entry will just be an i8**.
939
3
        src = Builder.CreateStructGEP(LoadBlockStruct(),
940
3
                                      enclosingCapture.getIndex(),
941
3
                                      "block.capture.addr");
942
257
      } else {
943
257
        auto I = LocalDeclMap.find(variable);
944
257
        assert(I != LocalDeclMap.end());
945
257
        src = I->second;
946
257
      }
947
1.95k
    } else {
948
1.95k
      DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
949
1.95k
                          /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
950
1.95k
                          type.getNonReferenceType(), VK_LValue,
951
1.95k
                          SourceLocation());
952
1.95k
      src = EmitDeclRefLValue(&declRef).getAddress(*this);
953
1.95k
    };
954
955
    // For byrefs, we just write the pointer to the byref struct into
956
    // the block field.  There's no need to chase the forwarding
957
    // pointer at this point, since we're building something that will
958
    // live a shorter life than the stack byref anyway.
959
2.23k
    if (CI.isEscapingByref()) {
960
      // Get a void* that points to the byref struct.
961
260
      llvm::Value *byrefPointer;
962
260
      if (CI.isNested())
963
3
        byrefPointer = Builder.CreateLoad(src, "byref.capture");
964
257
      else
965
257
        byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
966
967
      // Write that void* into the capture field.
968
260
      Builder.CreateStore(byrefPointer, blockField);
969
970
    // If we have a copy constructor, evaluate that into the block field.
971
1.97k
    } else if (const Expr *copyExpr = CI.getCopyExpr()) {
972
29
      if (blockDecl->isConversionFromLambda()) {
973
        // If we have a lambda conversion, emit the expression
974
        // directly into the block instead.
975
13
        AggValueSlot Slot =
976
13
            AggValueSlot::forAddr(blockField, Qualifiers(),
977
13
                                  AggValueSlot::IsDestructed,
978
13
                                  AggValueSlot::DoesNotNeedGCBarriers,
979
13
                                  AggValueSlot::IsNotAliased,
980
13
                                  AggValueSlot::DoesNotOverlap);
981
13
        EmitAggExpr(copyExpr, Slot);
982
16
      } else {
983
16
        EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
984
16
      }
985
986
    // If it's a reference variable, copy the reference into the block field.
987
1.94k
    } else if (type->isReferenceType()) {
988
405
      Builder.CreateStore(src.getPointer(), blockField);
989
990
    // If type is const-qualified, copy the value into the block field.
991
1.53k
    } else if (type.isConstQualified() &&
992
51
               type.getObjCLifetime() == Qualifiers::OCL_Strong &&
993
40
               CGM.getCodeGenOpts().OptimizationLevel != 0) {
994
4
      llvm::Value *value = Builder.CreateLoad(src, "captured");
995
4
      Builder.CreateStore(value, blockField);
996
997
    // If this is an ARC __strong block-pointer variable, don't do a
998
    // block copy.
999
    //
1000
    // TODO: this can be generalized into the normal initialization logic:
1001
    // we should never need to do a block-copy when initializing a local
1002
    // variable, because the local variable's lifetime should be strictly
1003
    // contained within the stack block's.
1004
1.53k
    } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1005
145
               type->isBlockPointerType()) {
1006
      // Load the block and do a simple retain.
1007
4
      llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1008
4
      value = EmitARCRetainNonBlock(value);
1009
1010
      // Do a primitive store to the block field.
1011
4
      Builder.CreateStore(value, blockField);
1012
1013
    // Otherwise, fake up a POD copy into the block field.
1014
1.53k
    } else {
1015
      // Fake up a new variable so that EmitScalarInit doesn't think
1016
      // we're referring to the variable in its own initializer.
1017
1.53k
      ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1018
1.53k
                                            ImplicitParamDecl::Other);
1019
1020
      // We use one of these or the other depending on whether the
1021
      // reference is nested.
1022
1.53k
      DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1023
1.53k
                          /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1024
1.53k
                          type, VK_LValue, SourceLocation());
1025
1026
1.53k
      ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1027
1.53k
                           &declRef, VK_RValue, FPOptionsOverride());
1028
      // FIXME: Pass a specific location for the expr init so that the store is
1029
      // attributed to a reasonable location - otherwise it may be attributed to
1030
      // locations of subexpressions in the initialization.
1031
1.53k
      EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1032
1.53k
                     MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1033
1.53k
                     /*captured by init*/ false);
1034
1.53k
    }
1035
1036
    // Push a cleanup for the capture if necessary.
1037
2.23k
    if (!blockInfo.NeedsCopyDispose)
1038
382
      continue;
1039
1040
    // Ignore __block captures; there's nothing special in the on-stack block
1041
    // that we need to do for them.
1042
1.85k
    if (CI.isByRef())
1043
260
      continue;
1044
1045
    // Ignore objects that aren't destructed.
1046
1.59k
    QualType::DestructionKind dtorKind = type.isDestructedType();
1047
1.59k
    if (dtorKind == QualType::DK_none)
1048
1.20k
      continue;
1049
1050
386
    CodeGenFunction::Destroyer *destroyer;
1051
1052
    // Block captures count as local values and have imprecise semantics.
1053
    // They also can't be arrays, so need to worry about that.
1054
    //
1055
    // For const-qualified captures, emit clang.arc.use to ensure the captured
1056
    // object doesn't get released while we are still depending on its validity
1057
    // within the block.
1058
386
    if (type.isConstQualified() &&
1059
43
        type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1060
40
        CGM.getCodeGenOpts().OptimizationLevel != 0) {
1061
4
      assert(CGM.getLangOpts().ObjCAutoRefCount &&
1062
4
             "expected ObjC ARC to be enabled");
1063
4
      destroyer = emitARCIntrinsicUse;
1064
382
    } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
1065
145
      destroyer = destroyARCStrongImprecise;
1066
237
    } else {
1067
237
      destroyer = getDestroyer(dtorKind);
1068
237
    }
1069
1070
386
    CleanupKind cleanupKind = NormalCleanup;
1071
386
    bool useArrayEHCleanup = needsEHCleanup(dtorKind);
1072
386
    if (useArrayEHCleanup)
1073
103
      cleanupKind = NormalAndEHCleanup;
1074
1075
    // Extend the lifetime of the capture to the end of the scope enclosing the
1076
    // block expression except when the block decl is in the list of RetExpr's
1077
    // cleanup objects, in which case its lifetime ends after the full
1078
    // expression.
1079
386
    auto IsBlockDeclInRetExpr = [&]() {
1080
386
      auto *EWC = llvm::dyn_cast_or_null<ExprWithCleanups>(RetExpr);
1081
386
      if (EWC)
1082
6
        for (auto &C : EWC->getObjects())
1083
4
          if (auto *BD = C.dyn_cast<BlockDecl *>())
1084
4
            if (BD == blockDecl)
1085
4
              return true;
1086
382
      return false;
1087
386
    };
1088
1089
386
    if (IsBlockDeclInRetExpr())
1090
4
      pushDestroy(cleanupKind, blockField, type, destroyer, useArrayEHCleanup);
1091
382
    else
1092
382
      pushLifetimeExtendedDestroy(cleanupKind, blockField, type, destroyer,
1093
382
                                  useArrayEHCleanup);
1094
386
  }
1095
1096
  // Cast to the converted block-pointer type, which happens (somewhat
1097
  // unfortunately) to be a pointer to function type.
1098
698
  llvm::Value *result = Builder.CreatePointerCast(
1099
698
      blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1100
1101
698
  if (IsOpenCL) {
1102
18
    CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1103
18
                                           result);
1104
18
  }
1105
1106
698
  return result;
1107
698
}
1108
1109
1110
2.21k
llvm::Type *CodeGenModule::getBlockDescriptorType() {
1111
2.21k
  if (BlockDescriptorType)
1112
1.78k
    return BlockDescriptorType;
1113
1114
429
  llvm::Type *UnsignedLongTy =
1115
429
    getTypes().ConvertType(getContext().UnsignedLongTy);
1116
1117
  // struct __block_descriptor {
1118
  //   unsigned long reserved;
1119
  //   unsigned long block_size;
1120
  //
1121
  //   // later, the following will be added
1122
  //
1123
  //   struct {
1124
  //     void (*copyHelper)();
1125
  //     void (*copyHelper)();
1126
  //   } helpers;                // !!! optional
1127
  //
1128
  //   const char *signature;   // the block signature
1129
  //   const char *layout;      // reserved
1130
  // };
1131
429
  BlockDescriptorType = llvm::StructType::create(
1132
429
      "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1133
1134
  // Now form a pointer to that.
1135
429
  unsigned AddrSpace = 0;
1136
429
  if (getLangOpts().OpenCL)
1137
14
    AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1138
429
  BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1139
429
  return BlockDescriptorType;
1140
429
}
1141
1142
614
llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1143
614
  if (GenericBlockLiteralType)
1144
347
    return GenericBlockLiteralType;
1145
1146
267
  llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1147
1148
267
  if (getLangOpts().OpenCL) {
1149
    // struct __opencl_block_literal_generic {
1150
    //   int __size;
1151
    //   int __align;
1152
    //   __generic void *__invoke;
1153
    //   /* custom fields */
1154
    // };
1155
14
    SmallVector<llvm::Type *, 8> StructFields(
1156
14
        {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1157
14
    if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1158
0
      for (auto I : Helper->getCustomFieldTypes())
1159
0
        StructFields.push_back(I);
1160
0
    }
1161
14
    GenericBlockLiteralType = llvm::StructType::create(
1162
14
        StructFields, "struct.__opencl_block_literal_generic");
1163
253
  } else {
1164
    // struct __block_literal_generic {
1165
    //   void *__isa;
1166
    //   int __flags;
1167
    //   int __reserved;
1168
    //   void (*__invoke)(void *);
1169
    //   struct __block_descriptor *__descriptor;
1170
    // };
1171
253
    GenericBlockLiteralType =
1172
253
        llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1173
253
                                 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1174
253
  }
1175
1176
267
  return GenericBlockLiteralType;
1177
267
}
1178
1179
RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1180
569
                                          ReturnValueSlot ReturnValue) {
1181
569
  const auto *BPT = E->getCallee()->getType()->castAs<BlockPointerType>();
1182
569
  llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1183
569
  llvm::Type *GenBlockTy = CGM.getGenericBlockLiteralType();
1184
569
  llvm::Value *Func = nullptr;
1185
569
  QualType FnType = BPT->getPointeeType();
1186
569
  ASTContext &Ctx = getContext();
1187
569
  CallArgList Args;
1188
1189
569
  if (getLangOpts().OpenCL) {
1190
    // For OpenCL, BlockPtr is already casted to generic block literal.
1191
1192
    // First argument of a block call is a generic block literal casted to
1193
    // generic void pointer, i.e. i8 addrspace(4)*
1194
18
    llvm::Value *BlockDescriptor = Builder.CreatePointerCast(
1195
18
        BlockPtr, CGM.getOpenCLRuntime().getGenericVoidPointerType());
1196
18
    QualType VoidPtrQualTy = Ctx.getPointerType(
1197
18
        Ctx.getAddrSpaceQualType(Ctx.VoidTy, LangAS::opencl_generic));
1198
18
    Args.add(RValue::get(BlockDescriptor), VoidPtrQualTy);
1199
    // And the rest of the arguments.
1200
18
    EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1201
1202
    // We *can* call the block directly unless it is a function argument.
1203
18
    if (!isa<ParmVarDecl>(E->getCalleeDecl()))
1204
18
      Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
1205
0
    else {
1206
0
      llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
1207
0
      Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1208
0
    }
1209
551
  } else {
1210
    // Bitcast the block literal to a generic block literal.
1211
551
    BlockPtr = Builder.CreatePointerCast(
1212
551
        BlockPtr, llvm::PointerType::get(GenBlockTy, 0), "block.literal");
1213
    // Get pointer to the block invoke function
1214
551
    llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
1215
1216
    // First argument is a block literal casted to a void pointer
1217
551
    BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
1218
551
    Args.add(RValue::get(BlockPtr), Ctx.VoidPtrTy);
1219
    // And the rest of the arguments.
1220
551
    EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1221
1222
    // Load the function.
1223
551
    Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1224
551
  }
1225
1226
569
  const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1227
569
  const CGFunctionInfo &FnInfo =
1228
569
    CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1229
1230
  // Cast the function pointer to the right type.
1231
569
  llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1232
1233
569
  llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1234
569
  Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1235
1236
  // Prepare the callee.
1237
569
  CGCallee Callee(CGCalleeInfo(), Func);
1238
1239
  // And call the block.
1240
569
  return EmitCall(FnInfo, Callee, ReturnValue, Args);
1241
569
}
1242
1243
5.15k
Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1244
5.15k
  assert(BlockInfo && "evaluating block ref without block information?");
1245
5.15k
  const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1246
1247
  // Handle constant captures.
1248
5.15k
  if (capture.isConstant()) 
return LocalDeclMap.find(variable)->second2
;
1249
1250
5.15k
  Address addr = Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1251
5.15k
                                         "block.capture.addr");
1252
1253
5.15k
  if (variable->isEscapingByref()) {
1254
    // addr should be a void** right now.  Load, then cast the result
1255
    // to byref*.
1256
1257
308
    auto &byrefInfo = getBlockByrefInfo(variable);
1258
308
    addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1259
1260
308
    auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1261
308
    addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1262
1263
308
    addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1264
308
                                 variable->getName());
1265
308
  }
1266
1267
5.15k
  assert((!variable->isNonEscapingByref() ||
1268
5.15k
          capture.fieldType()->isReferenceType()) &&
1269
5.15k
         "the capture field of a non-escaping variable should have a "
1270
5.15k
         "reference type");
1271
5.15k
  if (capture.fieldType()->isReferenceType())
1272
1.05k
    addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1273
1274
5.15k
  return addr;
1275
5.15k
}
1276
1277
void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1278
349
                                         llvm::Constant *Addr) {
1279
349
  bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1280
349
  (void)Ok;
1281
349
  assert(Ok && "Trying to replace an already-existing global block!");
1282
349
}
1283
1284
llvm::Constant *
1285
CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1286
80
                                    StringRef Name) {
1287
80
  if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1288
34
    return Block;
1289
1290
46
  CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1291
46
  blockInfo.BlockExpression = BE;
1292
1293
  // Compute information about the layout, etc., of this block.
1294
46
  computeBlockInfo(*this, nullptr, blockInfo);
1295
1296
  // Using that metadata, generate the actual block function.
1297
46
  {
1298
46
    CodeGenFunction::DeclMapTy LocalDeclMap;
1299
46
    CodeGenFunction(*this).GenerateBlockFunction(
1300
46
        GlobalDecl(), blockInfo, LocalDeclMap,
1301
46
        /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1302
46
  }
1303
1304
46
  return getAddrOfGlobalBlockIfEmitted(BE);
1305
46
}
1306
1307
static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1308
                                        const CGBlockInfo &blockInfo,
1309
349
                                        llvm::Constant *blockFn) {
1310
349
  assert(blockInfo.CanBeGlobal);
1311
  // Callers should detect this case on their own: calling this function
1312
  // generally requires computing layout information, which is a waste of time
1313
  // if we've already emitted this block.
1314
349
  assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1315
349
         "Refusing to re-emit a global block.");
1316
1317
  // Generate the constants for the block literal initializer.
1318
349
  ConstantInitBuilder builder(CGM);
1319
349
  auto fields = builder.beginStruct();
1320
1321
349
  bool IsOpenCL = CGM.getLangOpts().OpenCL;
1322
349
  bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1323
349
  if (!IsOpenCL) {
1324
    // isa
1325
295
    if (IsWindows)
1326
44
      fields.addNullPointer(CGM.Int8PtrPtrTy);
1327
251
    else
1328
251
      fields.add(CGM.getNSConcreteGlobalBlock());
1329
1330
    // __flags
1331
295
    BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1332
295
    if (blockInfo.UsesStret)
1333
7
      flags |= BLOCK_USE_STRET;
1334
1335
295
    fields.addInt(CGM.IntTy, flags.getBitMask());
1336
1337
    // Reserved
1338
295
    fields.addInt(CGM.IntTy, 0);
1339
54
  } else {
1340
54
    fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1341
54
    fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1342
54
  }
1343
1344
  // Function
1345
349
  fields.add(blockFn);
1346
1347
349
  if (!IsOpenCL) {
1348
    // Descriptor
1349
295
    fields.add(buildBlockDescriptor(CGM, blockInfo));
1350
54
  } else if (auto *Helper =
1351
0
                 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1352
0
    for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1353
0
      fields.add(I);
1354
0
    }
1355
0
  }
1356
1357
349
  unsigned AddrSpace = 0;
1358
349
  if (CGM.getContext().getLangOpts().OpenCL)
1359
54
    AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1360
1361
349
  llvm::GlobalVariable *literal = fields.finishAndCreateGlobal(
1362
349
      "__block_literal_global", blockInfo.BlockAlign,
1363
349
      /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1364
1365
349
  literal->addAttribute("objc_arc_inert");
1366
1367
  // Windows does not allow globals to be initialised to point to globals in
1368
  // different DLLs.  Any such variables must run code to initialise them.
1369
349
  if (IsWindows) {
1370
44
    auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1371
44
          {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1372
44
        &CGM.getModule());
1373
44
    llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1374
44
          Init));
1375
44
    b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1376
44
                         b.CreateStructGEP(literal, 0),
1377
44
                         CGM.getPointerAlign().getAsAlign());
1378
44
    b.CreateRetVoid();
1379
    // We can't use the normal LLVM global initialisation array, because we
1380
    // need to specify that this runs early in library initialisation.
1381
44
    auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1382
44
        /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1383
44
        Init, ".block_isa_init_ptr");
1384
44
    InitVar->setSection(".CRT$XCLa");
1385
44
    CGM.addUsedGlobal(InitVar);
1386
44
  }
1387
1388
  // Return a constant of the appropriately-casted type.
1389
349
  llvm::Type *RequiredType =
1390
349
    CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1391
349
  llvm::Constant *Result =
1392
349
      llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1393
349
  CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1394
349
  if (CGM.getContext().getLangOpts().OpenCL)
1395
54
    CGM.getOpenCLRuntime().recordBlockInfo(
1396
54
        blockInfo.BlockExpression,
1397
54
        cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1398
349
  return Result;
1399
349
}
1400
1401
void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1402
                                               unsigned argNum,
1403
1.04k
                                               llvm::Value *arg) {
1404
1.04k
  assert(BlockInfo && "not emitting prologue of block invocation function?!");
1405
1406
  // Allocate a stack slot like for any local variable to guarantee optimal
1407
  // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1408
1.04k
  Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1409
1.04k
  Builder.CreateStore(arg, alloc);
1410
1.04k
  if (CGDebugInfo *DI = getDebugInfo()) {
1411
163
    if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1412
159
      DI->setLocation(D->getLocation());
1413
159
      DI->EmitDeclareOfBlockLiteralArgVariable(
1414
159
          *BlockInfo, D->getName(), argNum,
1415
159
          cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1416
159
    }
1417
163
  }
1418
1419
1.04k
  SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1420
1.04k
  ApplyDebugLocation Scope(*this, StartLoc);
1421
1422
  // Instead of messing around with LocalDeclMap, just set the value
1423
  // directly as BlockPointer.
1424
1.04k
  BlockPointer = Builder.CreatePointerCast(
1425
1.04k
      arg,
1426
1.04k
      BlockInfo->StructureType->getPointerTo(
1427
1.04k
          getContext().getLangOpts().OpenCL
1428
72
              ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1429
975
              : 0),
1430
1.04k
      "block");
1431
1.04k
}
1432
1433
5.18k
Address CodeGenFunction::LoadBlockStruct() {
1434
5.18k
  assert(BlockInfo && "not in a block invocation function!");
1435
5.18k
  assert(BlockPointer && "no block pointer set!");
1436
5.18k
  return Address(BlockPointer, BlockInfo->BlockAlign);
1437
5.18k
}
1438
1439
llvm::Function *
1440
CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1441
                                       const CGBlockInfo &blockInfo,
1442
                                       const DeclMapTy &ldm,
1443
                                       bool IsLambdaConversionToBlock,
1444
1.04k
                                       bool BuildGlobalBlock) {
1445
1.04k
  const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1446
1447
1.04k
  CurGD = GD;
1448
1449
1.04k
  CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1450
1451
1.04k
  BlockInfo = &blockInfo;
1452
1453
  // Arrange for local static and local extern declarations to appear
1454
  // to be local to this function as well, in case they're directly
1455
  // referenced in a block.
1456
6.29k
  for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; 
++i5.25k
) {
1457
5.25k
    const auto *var = dyn_cast<VarDecl>(i->first);
1458
5.25k
    if (var && !var->hasLocalStorage())
1459
242
      setAddrOfLocalVar(var, i->second);
1460
5.25k
  }
1461
1462
  // Begin building the function declaration.
1463
1464
  // Build the argument list.
1465
1.04k
  FunctionArgList args;
1466
1467
  // The first argument is the block pointer.  Just take it as a void*
1468
  // and cast it later.
1469
1.04k
  QualType selfTy = getContext().VoidPtrTy;
1470
1471
  // For OpenCL passed block pointer can be private AS local variable or
1472
  // global AS program scope variable (for the case with and without captures).
1473
  // Generic AS is used therefore to be able to accommodate both private and
1474
  // generic AS in one implementation.
1475
1.04k
  if (getLangOpts().OpenCL)
1476
72
    selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1477
72
        getContext().VoidTy, LangAS::opencl_generic));
1478
1479
1.04k
  IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1480
1481
1.04k
  ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1482
1.04k
                             SourceLocation(), II, selfTy,
1483
1.04k
                             ImplicitParamDecl::ObjCSelf);
1484
1.04k
  args.push_back(&SelfDecl);
1485
1486
  // Now add the rest of the parameters.
1487
1.04k
  args.append(blockDecl->param_begin(), blockDecl->param_end());
1488
1489
  // Create the function declaration.
1490
1.04k
  const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1491
1.04k
  const CGFunctionInfo &fnInfo =
1492
1.04k
    CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1493
1.04k
  if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1494
9
    blockInfo.UsesStret = true;
1495
1496
1.04k
  llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1497
1498
1.04k
  StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1499
1.04k
  llvm::Function *fn = llvm::Function::Create(
1500
1.04k
      fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1501
1.04k
  CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1502
1503
1.04k
  if (BuildGlobalBlock) {
1504
349
    auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1505
54
                            ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1506
295
                            : VoidPtrTy;
1507
349
    buildGlobalBlock(CGM, blockInfo,
1508
349
                     llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1509
349
  }
1510
1511
  // Begin generating the function.
1512
1.04k
  StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1513
1.04k
                blockDecl->getLocation(),
1514
1.04k
                blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1515
1516
  // Okay.  Undo some of what StartFunction did.
1517
1518
  // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1519
  // won't delete the dbg.declare intrinsics for captured variables.
1520
1.04k
  llvm::Value *BlockPointerDbgLoc = BlockPointer;
1521
1.04k
  if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1522
    // Allocate a stack slot for it, so we can point the debugger to it
1523
958
    Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1524
958
                                      getPointerAlign(),
1525
958
                                      "block.addr");
1526
    // Set the DebugLocation to empty, so the store is recognized as a
1527
    // frame setup instruction by llvm::DwarfDebug::beginFunction().
1528
958
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
1529
958
    Builder.CreateStore(BlockPointer, Alloca);
1530
958
    BlockPointerDbgLoc = Alloca.getPointer();
1531
958
  }
1532
1533
  // If we have a C++ 'this' reference, go ahead and force it into
1534
  // existence now.
1535
1.04k
  if (blockDecl->capturesCXXThis()) {
1536
27
    Address addr = Builder.CreateStructGEP(
1537
27
        LoadBlockStruct(), blockInfo.CXXThisIndex, "block.captured-this");
1538
27
    CXXThisValue = Builder.CreateLoad(addr, "this");
1539
27
  }
1540
1541
  // Also force all the constant captures.
1542
2.23k
  for (const auto &CI : blockDecl->captures()) {
1543
2.23k
    const VarDecl *variable = CI.getVariable();
1544
2.23k
    const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1545
2.23k
    if (!capture.isConstant()) 
continue2.23k
;
1546
1547
5
    CharUnits align = getContext().getDeclAlign(variable);
1548
5
    Address alloca =
1549
5
      CreateMemTemp(variable->getType(), align, "block.captured-const");
1550
1551
5
    Builder.CreateStore(capture.getConstant(), alloca);
1552
1553
5
    setAddrOfLocalVar(variable, alloca);
1554
5
  }
1555
1556
  // Save a spot to insert the debug information for all the DeclRefExprs.
1557
1.04k
  llvm::BasicBlock *entry = Builder.GetInsertBlock();
1558
1.04k
  llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1559
1.04k
  --entry_ptr;
1560
1561
1.04k
  if (IsLambdaConversionToBlock)
1562
13
    EmitLambdaBlockInvokeBody();
1563
1.03k
  else {
1564
1.03k
    PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1565
1.03k
    incrementProfileCounter(blockDecl->getBody());
1566
1.03k
    EmitStmt(blockDecl->getBody());
1567
1.03k
  }
1568
1569
  // Remember where we were...
1570
1.04k
  llvm::BasicBlock *resume = Builder.GetInsertBlock();
1571
1572
  // Go back to the entry.
1573
1.04k
  ++entry_ptr;
1574
1.04k
  Builder.SetInsertPoint(entry, entry_ptr);
1575
1576
  // Emit debug information for all the DeclRefExprs.
1577
  // FIXME: also for 'this'
1578
1.04k
  if (CGDebugInfo *DI = getDebugInfo()) {
1579
1.15k
    for (const auto &CI : blockDecl->captures()) {
1580
1.15k
      const VarDecl *variable = CI.getVariable();
1581
1.15k
      DI->EmitLocation(Builder, variable->getLocation());
1582
1583
1.15k
      if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
1584
1.15k
        const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1585
1.15k
        if (capture.isConstant()) {
1586
0
          auto addr = LocalDeclMap.find(variable)->second;
1587
0
          (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1588
0
                                              Builder);
1589
0
          continue;
1590
0
        }
1591
1592
1.15k
        DI->EmitDeclareOfBlockDeclRefVariable(
1593
1.15k
            variable, BlockPointerDbgLoc, Builder, blockInfo,
1594
1.15k
            entry_ptr == entry->end() ? 
nullptr1
: &*entry_ptr);
1595
1.15k
      }
1596
1.15k
    }
1597
    // Recover location if it was changed in the above loop.
1598
163
    DI->EmitLocation(Builder,
1599
163
                     cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1600
163
  }
1601
1602
  // And resume where we left off.
1603
1.04k
  if (resume == nullptr)
1604
309
    Builder.ClearInsertionPoint();
1605
738
  else
1606
738
    Builder.SetInsertPoint(resume);
1607
1608
1.04k
  FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1609
1610
1.04k
  return fn;
1611
1.04k
}
1612
1613
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1614
computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1615
4.06k
                               const LangOptions &LangOpts) {
1616
4.06k
  if (CI.getCopyExpr()) {
1617
78
    assert(!CI.isByRef());
1618
    // don't bother computing flags
1619
78
    return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1620
78
  }
1621
3.98k
  BlockFieldFlags Flags;
1622
3.98k
  if (CI.isEscapingByref()) {
1623
610
    Flags = BLOCK_FIELD_IS_BYREF;
1624
610
    if (T.isObjCGCWeak())
1625
15
      Flags |= BLOCK_FIELD_IS_WEAK;
1626
610
    return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1627
610
  }
1628
1629
3.37k
  Flags = BLOCK_FIELD_IS_OBJECT;
1630
3.37k
  bool isBlockPointer = T->isBlockPointerType();
1631
3.37k
  if (isBlockPointer)
1632
26
    Flags = BLOCK_FIELD_IS_BLOCK;
1633
1634
3.37k
  switch (T.isNonTrivialToPrimitiveCopy()) {
1635
6
  case QualType::PCK_Struct:
1636
6
    return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1637
6
                          BlockFieldFlags());
1638
441
  case QualType::PCK_ARCWeak:
1639
    // We need to register __weak direct captures with the runtime.
1640
441
    return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1641
340
  case QualType::PCK_ARCStrong:
1642
    // We need to retain the copied value for __strong direct captures.
1643
    // If it's a block pointer, we have to copy the block and assign that to
1644
    // the destination pointer, so we might as well use _Block_object_assign.
1645
    // Otherwise we can avoid that.
1646
328
    return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1647
12
                                          : BlockCaptureEntityKind::BlockObject,
1648
340
                          Flags);
1649
2.58k
  case QualType::PCK_Trivial:
1650
2.58k
  case QualType::PCK_VolatileTrivial: {
1651
2.58k
    if (!T->isObjCRetainableType())
1652
      // For all other types, the memcpy is fine.
1653
2.41k
      return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1654
1655
    // Special rules for ARC captures:
1656
166
    Qualifiers QS = T.getQualifiers();
1657
1658
    // Non-ARC captures of retainable pointers are strong and
1659
    // therefore require a call to _Block_object_assign.
1660
166
    if (!QS.getObjCLifetime() && 
!LangOpts.ObjCAutoRefCount160
)
1661
160
      return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1662
1663
    // Otherwise the memcpy is fine.
1664
6
    return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1665
6
  }
1666
0
  }
1667
0
  llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1668
0
}
1669
1670
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1671
computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1672
                                  const LangOptions &LangOpts);
1673
1674
/// Find the set of block captures that need to be explicitly copied or destroy.
1675
static void findBlockCapturedManagedEntities(
1676
    const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1677
970
    SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
1678
4.06k
  for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1679
4.06k
    const VarDecl *Variable = CI.getVariable();
1680
4.06k
    const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1681
4.06k
    if (Capture.isConstant())
1682
2
      continue;
1683
1684
4.06k
    QualType VT = Capture.fieldType();
1685
4.06k
    auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1686
4.06k
    auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
1687
4.06k
    if (CopyInfo.first != BlockCaptureEntityKind::None ||
1688
2.42k
        DisposeInfo.first != BlockCaptureEntityKind::None)
1689
1.78k
      ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1690
1.78k
                                   CopyInfo.second, DisposeInfo.second, CI,
1691
1.78k
                                   Capture);
1692
4.06k
  }
1693
1694
  // Sort the captures by offset.
1695
970
  llvm::sort(ManagedCaptures);
1696
970
}
1697
1698
namespace {
1699
/// Release a __block variable.
1700
struct CallBlockRelease final : EHScopeStack::Cleanup {
1701
  Address Addr;
1702
  BlockFieldFlags FieldFlags;
1703
  bool LoadBlockVarAddr, CanThrow;
1704
1705
  CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1706
                   bool CT)
1707
      : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1708
515
        CanThrow(CT) {}
1709
1710
514
  void Emit(CodeGenFunction &CGF, Flags flags) override {
1711
514
    llvm::Value *BlockVarAddr;
1712
514
    if (LoadBlockVarAddr) {
1713
273
      BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1714
273
      BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1715
241
    } else {
1716
241
      BlockVarAddr = Addr.getPointer();
1717
241
    }
1718
1719
514
    CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1720
514
  }
1721
};
1722
} // end anonymous namespace
1723
1724
/// Check if \p T is a C++ class that has a destructor that can throw.
1725
829
bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1726
829
  if (const auto *RD = T->getAsCXXRecordDecl())
1727
48
    if (const CXXDestructorDecl *DD = RD->getDestructor())
1728
42
      return DD->getType()->castAs<FunctionProtoType>()->canThrow();
1729
787
  return false;
1730
787
}
1731
1732
// Return a string that has the information about a capture.
1733
static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1734
                                      CaptureStrKind StrKind,
1735
                                      CharUnits BlockAlignment,
1736
1.80k
                                      CodeGenModule &CGM) {
1737
1.80k
  std::string Str;
1738
1.80k
  ASTContext &Ctx = CGM.getContext();
1739
1.80k
  const BlockDecl::Capture &CI = *E.CI;
1740
1.80k
  QualType CaptureTy = CI.getVariable()->getType();
1741
1742
1.80k
  BlockCaptureEntityKind Kind;
1743
1.80k
  BlockFieldFlags Flags;
1744
1745
  // CaptureStrKind::Merged should be passed only when the operations and the
1746
  // flags are the same for copy and dispose.
1747
1.80k
  assert((StrKind != CaptureStrKind::Merged ||
1748
1.80k
          (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1749
1.80k
         "different operations and flags");
1750
1751
1.80k
  if (StrKind == CaptureStrKind::DisposeHelper) {
1752
669
    Kind = E.DisposeKind;
1753
669
    Flags = E.DisposeFlags;
1754
1.13k
  } else {
1755
1.13k
    Kind = E.CopyKind;
1756
1.13k
    Flags = E.CopyFlags;
1757
1.13k
  }
1758
1759
1.80k
  switch (Kind) {
1760
140
  case BlockCaptureEntityKind::CXXRecord: {
1761
140
    Str += "c";
1762
140
    SmallString<256> TyStr;
1763
140
    llvm::raw_svector_ostream Out(TyStr);
1764
140
    CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1765
140
    Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1766
140
    break;
1767
0
  }
1768
441
  case BlockCaptureEntityKind::ARCWeak:
1769
441
    Str += "w";
1770
441
    break;
1771
336
  case BlockCaptureEntityKind::ARCStrong:
1772
336
    Str += "s";
1773
336
    break;
1774
778
  case BlockCaptureEntityKind::BlockObject: {
1775
778
    const VarDecl *Var = CI.getVariable();
1776
778
    unsigned F = Flags.getBitMask();
1777
778
    if (F & BLOCK_FIELD_IS_BYREF) {
1778
610
      Str += "r";
1779
610
      if (F & BLOCK_FIELD_IS_WEAK)
1780
15
        Str += "w";
1781
595
      else {
1782
        // If CaptureStrKind::Merged is passed, check both the copy expression
1783
        // and the destructor.
1784
595
        if (StrKind != CaptureStrKind::DisposeHelper) {
1785
358
          if (Ctx.getBlockVarCopyInit(Var).canThrow())
1786
12
            Str += "c";
1787
358
        }
1788
595
        if (StrKind != CaptureStrKind::CopyHelper) {
1789
358
          if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1790
2
            Str += "d";
1791
358
        }
1792
595
      }
1793
168
    } else {
1794
168
      assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1795
168
      if (F == BLOCK_FIELD_IS_BLOCK)
1796
22
        Str += "b";
1797
146
      else
1798
146
        Str += "o";
1799
168
    }
1800
778
    break;
1801
0
  }
1802
6
  case BlockCaptureEntityKind::NonTrivialCStruct: {
1803
6
    bool IsVolatile = CaptureTy.isVolatileQualified();
1804
6
    CharUnits Alignment =
1805
6
        BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1806
1807
6
    Str += "n";
1808
6
    std::string FuncStr;
1809
6
    if (StrKind == CaptureStrKind::DisposeHelper)
1810
2
      FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1811
2
          CaptureTy, Alignment, IsVolatile, Ctx);
1812
4
    else
1813
      // If CaptureStrKind::Merged is passed, use the copy constructor string.
1814
      // It has all the information that the destructor string has.
1815
4
      FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1816
4
          CaptureTy, Alignment, IsVolatile, Ctx);
1817
    // The underscore is necessary here because non-trivial copy constructor
1818
    // and destructor strings can start with a number.
1819
6
    Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1820
6
    break;
1821
0
  }
1822
103
  case BlockCaptureEntityKind::None:
1823
103
    break;
1824
1.80k
  }
1825
1826
1.80k
  return Str;
1827
1.80k
}
1828
1829
static std::string getCopyDestroyHelperFuncName(
1830
    const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1831
730
    CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1832
730
  assert((StrKind == CaptureStrKind::CopyHelper ||
1833
730
          StrKind == CaptureStrKind::DisposeHelper) &&
1834
730
         "unexpected CaptureStrKind");
1835
730
  std::string Name = StrKind == CaptureStrKind::CopyHelper
1836
365
                         ? "__copy_helper_block_"
1837
365
                         : "__destroy_helper_block_";
1838
730
  if (CGM.getLangOpts().Exceptions)
1839
238
    Name += "e";
1840
730
  if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1841
14
    Name += "a";
1842
730
  Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1843
1844
1.29k
  for (const BlockCaptureManagedEntity &E : Captures) {
1845
1.29k
    Name += llvm::to_string(E.Capture->getOffset().getQuantity());
1846
1.29k
    Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
1847
1.29k
  }
1848
1849
730
  return Name;
1850
730
}
1851
1852
static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1853
                               Address Field, QualType CaptureType,
1854
                               BlockFieldFlags Flags, bool ForCopyHelper,
1855
1.11k
                               VarDecl *Var, CodeGenFunction &CGF) {
1856
1.11k
  bool EHOnly = ForCopyHelper;
1857
1858
1.11k
  switch (CaptureKind) {
1859
579
  case BlockCaptureEntityKind::CXXRecord:
1860
579
  case BlockCaptureEntityKind::ARCWeak:
1861
579
  case BlockCaptureEntityKind::NonTrivialCStruct:
1862
579
  case BlockCaptureEntityKind::ARCStrong: {
1863
579
    if (CaptureType.isDestructedType() &&
1864
565
        (!EHOnly || 
CGF.needsEHCleanup(CaptureType.isDestructedType())246
)) {
1865
330
      CodeGenFunction::Destroyer *Destroyer =
1866
330
          CaptureKind == BlockCaptureEntityKind::ARCStrong
1867
86
              ? CodeGenFunction::destroyARCStrongImprecise
1868
244
              : CGF.getDestroyer(CaptureType.isDestructedType());
1869
330
      CleanupKind Kind =
1870
11
          EHOnly ? EHCleanup
1871
319
                 : CGF.getCleanupKind(CaptureType.isDestructedType());
1872
330
      CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1873
330
    }
1874
579
    break;
1875
579
  }
1876
532
  case BlockCaptureEntityKind::BlockObject: {
1877
532
    if (!EHOnly || 
CGF.getLangOpts().Exceptions266
) {
1878
266
      CleanupKind Kind = EHOnly ? 
EHCleanup44
: NormalAndEHCleanup;
1879
      // Calls to _Block_object_dispose along the EH path in the copy helper
1880
      // function don't throw as newly-copied __block variables always have a
1881
      // reference count of 2.
1882
310
      bool CanThrow =
1883
310
          !ForCopyHelper && 
CGF.cxxDestructorCanThrow(CaptureType)266
;
1884
310
      CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1885
310
                            CanThrow);
1886
310
    }
1887
532
    break;
1888
579
  }
1889
7
  case BlockCaptureEntityKind::None:
1890
7
    break;
1891
1.11k
  }
1892
1.11k
}
1893
1894
static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1895
                                               llvm::Function *Fn,
1896
                                               const CGFunctionInfo &FI,
1897
658
                                               CodeGenModule &CGM) {
1898
658
  if (CapturesNonExternalType) {
1899
19
    CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1900
639
  } else {
1901
639
    Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1902
639
    Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1903
639
    CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
1904
639
    CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1905
639
  }
1906
658
}
1907
/// Generate the copy-helper function for a block closure object:
1908
///   static void block_copy_helper(block_t *dst, block_t *src);
1909
/// The runtime will have previously initialized 'dst' by doing a
1910
/// bit-copy of 'src'.
1911
///
1912
/// Note that this copies an entire block closure object to the heap;
1913
/// it should not be confused with a 'byref copy helper', which moves
1914
/// the contents of an individual __block variable to the heap.
1915
llvm::Constant *
1916
365
CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1917
365
  SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1918
365
  findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
1919
365
  std::string FuncName =
1920
365
      getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
1921
365
                                   CaptureStrKind::CopyHelper, CGM);
1922
1923
365
  if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
1924
32
    return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
1925
1926
333
  ASTContext &C = getContext();
1927
1928
333
  QualType ReturnTy = C.VoidTy;
1929
1930
333
  FunctionArgList args;
1931
333
  ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1932
333
  args.push_back(&DstDecl);
1933
333
  ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
1934
333
  args.push_back(&SrcDecl);
1935
1936
333
  const CGFunctionInfo &FI =
1937
333
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
1938
1939
  // FIXME: it would be nice if these were mergeable with things with
1940
  // identical semantics.
1941
333
  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1942
1943
333
  llvm::Function *Fn =
1944
333
    llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
1945
333
                           FuncName, &CGM.getModule());
1946
333
  if (CGM.supportsCOMDAT())
1947
58
    Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
1948
1949
333
  IdentifierInfo *II = &C.Idents.get(FuncName);
1950
1951
333
  SmallVector<QualType, 2> ArgTys;
1952
333
  ArgTys.push_back(C.VoidPtrTy);
1953
333
  ArgTys.push_back(C.VoidPtrTy);
1954
333
  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
1955
1956
333
  FunctionDecl *FD = FunctionDecl::Create(
1957
333
      C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
1958
333
      FunctionTy, nullptr, SC_Static, false, false);
1959
333
  setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
1960
333
                                     CGM);
1961
  // This is necessary to avoid inheriting the previous line number.
1962
333
  FD->setImplicit();
1963
333
  StartFunction(FD, ReturnTy, Fn, FI, args);
1964
333
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
1965
1966
333
  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1967
1968
333
  Address src = GetAddrOfLocalVar(&SrcDecl);
1969
333
  src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1970
333
  src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1971
1972
333
  Address dst = GetAddrOfLocalVar(&DstDecl);
1973
333
  dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1974
333
  dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1975
1976
599
  for (const auto &CopiedCapture : CopiedCaptures) {
1977
599
    const BlockDecl::Capture &CI = *CopiedCapture.CI;
1978
599
    const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
1979
599
    QualType captureType = CI.getVariable()->getType();
1980
599
    BlockFieldFlags flags = CopiedCapture.CopyFlags;
1981
1982
599
    unsigned index = capture.getIndex();
1983
599
    Address srcField = Builder.CreateStructGEP(src, index);
1984
599
    Address dstField = Builder.CreateStructGEP(dst, index);
1985
1986
599
    switch (CopiedCapture.CopyKind) {
1987
29
    case BlockCaptureEntityKind::CXXRecord:
1988
      // If there's an explicit copy expression, we do that.
1989
29
      assert(CI.getCopyExpr() && "copy expression for variable is missing");
1990
29
      EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1991
29
      break;
1992
147
    case BlockCaptureEntityKind::ARCWeak:
1993
147
      EmitARCCopyWeak(dstField, srcField);
1994
147
      break;
1995
2
    case BlockCaptureEntityKind::NonTrivialCStruct: {
1996
      // If this is a C struct that requires non-trivial copy construction,
1997
      // emit a call to its copy constructor.
1998
2
      QualType varType = CI.getVariable()->getType();
1999
2
      callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2000
2
                                 MakeAddrLValue(srcField, varType));
2001
2
      break;
2002
0
    }
2003
82
    case BlockCaptureEntityKind::ARCStrong: {
2004
82
      llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2005
      // At -O0, store null into the destination field (so that the
2006
      // storeStrong doesn't over-release) and then call storeStrong.
2007
      // This is a workaround to not having an initStrong call.
2008
82
      if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2009
78
        auto *ty = cast<llvm::PointerType>(srcValue->getType());
2010
78
        llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2011
78
        Builder.CreateStore(null, dstField);
2012
78
        EmitARCStoreStrongCall(dstField, srcValue, true);
2013
2014
      // With optimization enabled, take advantage of the fact that
2015
      // the blocks runtime guarantees a memcpy of the block data, and
2016
      // just emit a retain of the src field.
2017
4
      } else {
2018
4
        EmitARCRetainNonBlock(srcValue);
2019
2020
        // Unless EH cleanup is required, we don't need this anymore, so kill
2021
        // it. It's not quite worth the annoyance to avoid creating it in the
2022
        // first place.
2023
4
        if (!needsEHCleanup(captureType.isDestructedType()))
2024
2
          cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
2025
4
      }
2026
82
      break;
2027
0
    }
2028
266
    case BlockCaptureEntityKind::BlockObject: {
2029
266
      llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2030
266
      srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2031
266
      llvm::Value *dstAddr =
2032
266
          Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2033
266
      llvm::Value *args[] = {
2034
266
        dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2035
266
      };
2036
2037
266
      if (CI.isByRef() && 
C.getBlockVarCopyInit(CI.getVariable()).canThrow()210
)
2038
10
        EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2039
256
      else
2040
256
        EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2041
266
      break;
2042
0
    }
2043
73
    case BlockCaptureEntityKind::None:
2044
73
      continue;
2045
526
    }
2046
2047
    // Ensure that we destroy the copied object if an exception is thrown later
2048
    // in the helper function.
2049
526
    pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
2050
526
                       /*ForCopyHelper*/ true, CI.getVariable(), *this);
2051
526
  }
2052
2053
333
  FinishFunction();
2054
2055
333
  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2056
333
}
2057
2058
static BlockFieldFlags
2059
getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2060
941
                                       QualType T) {
2061
941
  BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2062
941
  if (T->isBlockPointerType())
2063
26
    Flags = BLOCK_FIELD_IS_BLOCK;
2064
941
  return Flags;
2065
941
}
2066
2067
static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2068
computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2069
4.06k
                                  const LangOptions &LangOpts) {
2070
4.06k
  if (CI.isEscapingByref()) {
2071
610
    BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2072
610
    if (T.isObjCGCWeak())
2073
15
      Flags |= BLOCK_FIELD_IS_WEAK;
2074
610
    return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2075
610
  }
2076
2077
3.45k
  switch (T.isDestructedType()) {
2078
186
  case QualType::DK_cxx_destructor:
2079
186
    return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2080
340
  case QualType::DK_objc_strong_lifetime:
2081
    // Use objc_storeStrong for __strong direct captures; the
2082
    // dynamic tools really like it when we do this.
2083
340
    return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2084
340
                          getBlockFieldFlagsForObjCObjectPointer(CI, T));
2085
441
  case QualType::DK_objc_weak_lifetime:
2086
    // Support __weak direct captures.
2087
441
    return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2088
441
                          getBlockFieldFlagsForObjCObjectPointer(CI, T));
2089
6
  case QualType::DK_nontrivial_c_struct:
2090
6
    return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2091
6
                          BlockFieldFlags());
2092
2.47k
  case QualType::DK_none: {
2093
    // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2094
2.47k
    if (T->isObjCRetainableType() && 
!T.getQualifiers().hasObjCLifetime()166
&&
2095
160
        !LangOpts.ObjCAutoRefCount)
2096
160
      return std::make_pair(BlockCaptureEntityKind::BlockObject,
2097
160
                            getBlockFieldFlagsForObjCObjectPointer(CI, T));
2098
    // Otherwise, we have nothing to do.
2099
2.31k
    return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2100
2.31k
  }
2101
0
  }
2102
0
  llvm_unreachable("after exhaustive DestructionKind switch");
2103
0
}
2104
2105
/// Generate the destroy-helper function for a block closure object:
2106
///   static void block_destroy_helper(block_t *theBlock);
2107
///
2108
/// Note that this destroys a heap-allocated block closure object;
2109
/// it should not be confused with a 'byref destroy helper', which
2110
/// destroys the heap-allocated contents of an individual __block
2111
/// variable.
2112
llvm::Constant *
2113
365
CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2114
365
  SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
2115
365
  findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
2116
365
  std::string FuncName =
2117
365
      getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
2118
365
                                   CaptureStrKind::DisposeHelper, CGM);
2119
2120
365
  if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2121
40
    return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2122
2123
325
  ASTContext &C = getContext();
2124
2125
325
  QualType ReturnTy = C.VoidTy;
2126
2127
325
  FunctionArgList args;
2128
325
  ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2129
325
  args.push_back(&SrcDecl);
2130
2131
325
  const CGFunctionInfo &FI =
2132
325
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2133
2134
  // FIXME: We'd like to put these into a mergable by content, with
2135
  // internal linkage.
2136
325
  llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2137
2138
325
  llvm::Function *Fn =
2139
325
    llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2140
325
                           FuncName, &CGM.getModule());
2141
325
  if (CGM.supportsCOMDAT())
2142
58
    Fn->setComdat(CGM.getModule().getOrInsertComdat(FuncName));
2143
2144
325
  IdentifierInfo *II = &C.Idents.get(FuncName);
2145
2146
325
  SmallVector<QualType, 1> ArgTys;
2147
325
  ArgTys.push_back(C.VoidPtrTy);
2148
325
  QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2149
2150
325
  FunctionDecl *FD = FunctionDecl::Create(
2151
325
      C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2152
325
      FunctionTy, nullptr, SC_Static, false, false);
2153
2154
325
  setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2155
325
                                     CGM);
2156
  // This is necessary to avoid inheriting the previous line number.
2157
325
  FD->setImplicit();
2158
325
  StartFunction(FD, ReturnTy, Fn, FI, args);
2159
325
  markAsIgnoreThreadCheckingAtRuntime(Fn);
2160
2161
325
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
2162
2163
325
  llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2164
2165
325
  Address src = GetAddrOfLocalVar(&SrcDecl);
2166
325
  src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2167
325
  src = Builder.CreateBitCast(src, structPtrTy, "block");
2168
2169
325
  CodeGenFunction::RunCleanupsScope cleanups(*this);
2170
2171
592
  for (const auto &DestroyedCapture : DestroyedCaptures) {
2172
592
    const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2173
592
    const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
2174
592
    BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
2175
2176
592
    Address srcField = Builder.CreateStructGEP(src, capture.getIndex());
2177
2178
592
    pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
2179
592
                       CI.getVariable()->getType(), flags,
2180
592
                       /*ForCopyHelper*/ false, CI.getVariable(), *this);
2181
592
  }
2182
2183
325
  cleanups.ForceCleanup();
2184
2185
325
  FinishFunction();
2186
2187
325
  return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2188
325
}
2189
2190
namespace {
2191
2192
/// Emits the copy/dispose helper functions for a __block object of id type.
2193
class ObjectByrefHelpers final : public BlockByrefHelpers {
2194
  BlockFieldFlags Flags;
2195
2196
public:
2197
  ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2198
24
    : BlockByrefHelpers(alignment), Flags(flags) {}
2199
2200
  void emitCopy(CodeGenFunction &CGF, Address destField,
2201
18
                Address srcField) override {
2202
18
    destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2203
2204
18
    srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2205
18
    llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2206
2207
18
    unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2208
2209
18
    llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2210
18
    llvm::FunctionCallee fn = CGF.CGM.getBlockObjectAssign();
2211
2212
18
    llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2213
18
    CGF.EmitNounwindRuntimeCall(fn, args);
2214
18
  }
2215
2216
18
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2217
18
    field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2218
18
    llvm::Value *value = CGF.Builder.CreateLoad(field);
2219
2220
18
    CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2221
18
  }
2222
2223
30
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2224
30
    id.AddInteger(Flags.getBitMask());
2225
30
  }
2226
};
2227
2228
/// Emits the copy/dispose helpers for an ARC __block __weak variable.
2229
class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2230
public:
2231
7
  ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2232
2233
  void emitCopy(CodeGenFunction &CGF, Address destField,
2234
7
                Address srcField) override {
2235
7
    CGF.EmitARCMoveWeak(destField, srcField);
2236
7
  }
2237
2238
7
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2239
7
    CGF.EmitARCDestroyWeak(field);
2240
7
  }
2241
2242
7
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2243
    // 0 is distinguishable from all pointers and byref flags
2244
7
    id.AddInteger(0);
2245
7
  }
2246
};
2247
2248
/// Emits the copy/dispose helpers for an ARC __block __strong variable
2249
/// that's not of block-pointer type.
2250
class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2251
public:
2252
21
  ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2253
2254
  void emitCopy(CodeGenFunction &CGF, Address destField,
2255
13
                Address srcField) override {
2256
    // Do a "move" by copying the value and then zeroing out the old
2257
    // variable.
2258
2259
13
    llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2260
2261
13
    llvm::Value *null =
2262
13
      llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2263
2264
13
    if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2265
11
      CGF.Builder.CreateStore(null, destField);
2266
11
      CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2267
11
      CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2268
11
      return;
2269
11
    }
2270
2
    CGF.Builder.CreateStore(value, destField);
2271
2
    CGF.Builder.CreateStore(null, srcField);
2272
2
  }
2273
2274
13
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2275
13
    CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2276
13
  }
2277
2278
29
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2279
    // 1 is distinguishable from all pointers and byref flags
2280
29
    id.AddInteger(1);
2281
29
  }
2282
};
2283
2284
/// Emits the copy/dispose helpers for an ARC __block __strong
2285
/// variable that's of block-pointer type.
2286
class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2287
public:
2288
  ARCStrongBlockByrefHelpers(CharUnits alignment)
2289
4
    : BlockByrefHelpers(alignment) {}
2290
2291
  void emitCopy(CodeGenFunction &CGF, Address destField,
2292
2
                Address srcField) override {
2293
    // Do the copy with objc_retainBlock; that's all that
2294
    // _Block_object_assign would do anyway, and we'd have to pass the
2295
    // right arguments to make sure it doesn't get no-op'ed.
2296
2
    llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2297
2
    llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2298
2
    CGF.Builder.CreateStore(copy, destField);
2299
2
  }
2300
2301
2
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2302
2
    CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2303
2
  }
2304
2305
6
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2306
    // 2 is distinguishable from all pointers and byref flags
2307
6
    id.AddInteger(2);
2308
6
  }
2309
};
2310
2311
/// Emits the copy/dispose helpers for a __block variable with a
2312
/// nontrivial copy constructor or destructor.
2313
class CXXByrefHelpers final : public BlockByrefHelpers {
2314
  QualType VarType;
2315
  const Expr *CopyExpr;
2316
2317
public:
2318
  CXXByrefHelpers(CharUnits alignment, QualType type,
2319
                  const Expr *copyExpr)
2320
15
    : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2321
2322
12
  bool needsCopy() const override { return CopyExpr != nullptr; }
2323
  void emitCopy(CodeGenFunction &CGF, Address destField,
2324
12
                Address srcField) override {
2325
12
    if (!CopyExpr) 
return0
;
2326
12
    CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2327
12
  }
2328
2329
12
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2330
12
    EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2331
12
    CGF.PushDestructorCleanup(VarType, field);
2332
12
    CGF.PopCleanupBlocks(cleanupDepth);
2333
12
  }
2334
2335
18
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2336
18
    id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2337
18
  }
2338
};
2339
2340
/// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2341
/// C struct.
2342
class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2343
  QualType VarType;
2344
2345
public:
2346
  NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2347
9
    : BlockByrefHelpers(alignment), VarType(type) {}
2348
2349
  void emitCopy(CodeGenFunction &CGF, Address destField,
2350
9
                Address srcField) override {
2351
9
    CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2352
9
                                   CGF.MakeAddrLValue(srcField, VarType));
2353
9
  }
2354
2355
9
  bool needsDispose() const override {
2356
9
    return VarType.isDestructedType();
2357
9
  }
2358
2359
9
  void emitDispose(CodeGenFunction &CGF, Address field) override {
2360
9
    EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2361
9
    CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2362
9
    CGF.PopCleanupBlocks(cleanupDepth);
2363
9
  }
2364
2365
9
  void profileImpl(llvm::FoldingSetNodeID &id) const override {
2366
9
    id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2367
9
  }
2368
};
2369
} // end anonymous namespace
2370
2371
static llvm::Constant *
2372
generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2373
61
                        BlockByrefHelpers &generator) {
2374
61
  ASTContext &Context = CGF.getContext();
2375
2376
61
  QualType ReturnTy = Context.VoidTy;
2377
2378
61
  FunctionArgList args;
2379
61
  ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2380
61
  args.push_back(&Dst);
2381
2382
61
  ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2383
61
  args.push_back(&Src);
2384
2385
61
  const CGFunctionInfo &FI =
2386
61
      CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2387
2388
61
  llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2389
2390
  // FIXME: We'd like to put these into a mergable by content, with
2391
  // internal linkage.
2392
61
  llvm::Function *Fn =
2393
61
    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2394
61
                           "__Block_byref_object_copy_", &CGF.CGM.getModule());
2395
2396
61
  IdentifierInfo *II
2397
61
    = &Context.Idents.get("__Block_byref_object_copy_");
2398
2399
61
  SmallVector<QualType, 2> ArgTys;
2400
61
  ArgTys.push_back(Context.VoidPtrTy);
2401
61
  ArgTys.push_back(Context.VoidPtrTy);
2402
61
  QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2403
2404
61
  FunctionDecl *FD = FunctionDecl::Create(
2405
61
      Context, Context.getTranslationUnitDecl(), SourceLocation(),
2406
61
      SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2407
2408
61
  CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2409
2410
61
  CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
2411
2412
61
  if (generator.needsCopy()) {
2413
61
    llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
2414
2415
    // dst->x
2416
61
    Address destField = CGF.GetAddrOfLocalVar(&Dst);
2417
61
    destField = Address(CGF.Builder.CreateLoad(destField),
2418
61
                        byrefInfo.ByrefAlignment);
2419
61
    destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
2420
61
    destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2421
61
                                          "dest-object");
2422
2423
    // src->x
2424
61
    Address srcField = CGF.GetAddrOfLocalVar(&Src);
2425
61
    srcField = Address(CGF.Builder.CreateLoad(srcField),
2426
61
                       byrefInfo.ByrefAlignment);
2427
61
    srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
2428
61
    srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2429
61
                                         "src-object");
2430
2431
61
    generator.emitCopy(CGF, destField, srcField);
2432
61
  }
2433
2434
61
  CGF.FinishFunction();
2435
2436
61
  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2437
61
}
2438
2439
/// Build the copy helper for a __block variable.
2440
static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2441
                                            const BlockByrefInfo &byrefInfo,
2442
61
                                            BlockByrefHelpers &generator) {
2443
61
  CodeGenFunction CGF(CGM);
2444
61
  return generateByrefCopyHelper(CGF, byrefInfo, generator);
2445
61
}
2446
2447
/// Generate code for a __block variable's dispose helper.
2448
static llvm::Constant *
2449
generateByrefDisposeHelper(CodeGenFunction &CGF,
2450
                           const BlockByrefInfo &byrefInfo,
2451
61
                           BlockByrefHelpers &generator) {
2452
61
  ASTContext &Context = CGF.getContext();
2453
61
  QualType R = Context.VoidTy;
2454
2455
61
  FunctionArgList args;
2456
61
  ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2457
61
                        ImplicitParamDecl::Other);
2458
61
  args.push_back(&Src);
2459
2460
61
  const CGFunctionInfo &FI =
2461
61
    CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2462
2463
61
  llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2464
2465
  // FIXME: We'd like to put these into a mergable by content, with
2466
  // internal linkage.
2467
61
  llvm::Function *Fn =
2468
61
    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2469
61
                           "__Block_byref_object_dispose_",
2470
61
                           &CGF.CGM.getModule());
2471
2472
61
  IdentifierInfo *II
2473
61
    = &Context.Idents.get("__Block_byref_object_dispose_");
2474
2475
61
  SmallVector<QualType, 1> ArgTys;
2476
61
  ArgTys.push_back(Context.VoidPtrTy);
2477
61
  QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2478
2479
61
  FunctionDecl *FD = FunctionDecl::Create(
2480
61
      Context, Context.getTranslationUnitDecl(), SourceLocation(),
2481
61
      SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2482
2483
61
  CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2484
2485
61
  CGF.StartFunction(FD, R, Fn, FI, args);
2486
2487
61
  if (generator.needsDispose()) {
2488
61
    Address addr = CGF.GetAddrOfLocalVar(&Src);
2489
61
    addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2490
61
    auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2491
61
    addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2492
61
    addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2493
2494
61
    generator.emitDispose(CGF, addr);
2495
61
  }
2496
2497
61
  CGF.FinishFunction();
2498
2499
61
  return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2500
61
}
2501
2502
/// Build the dispose helper for a __block variable.
2503
static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2504
                                               const BlockByrefInfo &byrefInfo,
2505
61
                                               BlockByrefHelpers &generator) {
2506
61
  CodeGenFunction CGF(CGM);
2507
61
  return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2508
61
}
2509
2510
/// Lazily build the copy and dispose helpers for a __block variable
2511
/// with the given information.
2512
template <class T>
2513
static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2514
80
                            T &&generator) {
2515
80
  llvm::FoldingSetNodeID id;
2516
80
  generator.Profile(id);
2517
2518
80
  void *insertPos;
2519
80
  BlockByrefHelpers *node
2520
80
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
80
  if (node) 
return static_cast<T*>(node)19
;
2522
2523
61
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
61
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
61
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
61
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
61
  return copy;
2529
61
}
CGBlocks.cpp:(anonymous namespace)::CXXByrefHelpers* buildByrefHelpers<(anonymous namespace)::CXXByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::CXXByrefHelpers&&)
Line
Count
Source
2514
15
                            T &&generator) {
2515
15
  llvm::FoldingSetNodeID id;
2516
15
  generator.Profile(id);
2517
2518
15
  void *insertPos;
2519
15
  BlockByrefHelpers *node
2520
15
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
15
  if (node) 
return static_cast<T*>(node)3
;
2522
2523
12
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
12
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
12
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
12
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
12
  return copy;
2529
12
}
CGBlocks.cpp:(anonymous namespace)::NonTrivialCStructByrefHelpers* buildByrefHelpers<(anonymous namespace)::NonTrivialCStructByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::NonTrivialCStructByrefHelpers&&)
Line
Count
Source
2514
9
                            T &&generator) {
2515
9
  llvm::FoldingSetNodeID id;
2516
9
  generator.Profile(id);
2517
2518
9
  void *insertPos;
2519
9
  BlockByrefHelpers *node
2520
9
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
9
  if (node) 
return static_cast<T*>(node)0
;
2522
2523
9
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
9
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
9
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
9
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
9
  return copy;
2529
9
}
CGBlocks.cpp:(anonymous namespace)::ARCWeakByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCWeakByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCWeakByrefHelpers&&)
Line
Count
Source
2514
7
                            T &&generator) {
2515
7
  llvm::FoldingSetNodeID id;
2516
7
  generator.Profile(id);
2517
2518
7
  void *insertPos;
2519
7
  BlockByrefHelpers *node
2520
7
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
7
  if (node) 
return static_cast<T*>(node)0
;
2522
2523
7
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
7
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
7
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
7
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
7
  return copy;
2529
7
}
CGBlocks.cpp:(anonymous namespace)::ARCStrongBlockByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCStrongBlockByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCStrongBlockByrefHelpers&&)
Line
Count
Source
2514
4
                            T &&generator) {
2515
4
  llvm::FoldingSetNodeID id;
2516
4
  generator.Profile(id);
2517
2518
4
  void *insertPos;
2519
4
  BlockByrefHelpers *node
2520
4
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
4
  if (node) 
return static_cast<T*>(node)2
;
2522
2523
2
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
2
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
2
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
2
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
2
  return copy;
2529
2
}
CGBlocks.cpp:(anonymous namespace)::ARCStrongByrefHelpers* buildByrefHelpers<(anonymous namespace)::ARCStrongByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ARCStrongByrefHelpers&&)
Line
Count
Source
2514
21
                            T &&generator) {
2515
21
  llvm::FoldingSetNodeID id;
2516
21
  generator.Profile(id);
2517
2518
21
  void *insertPos;
2519
21
  BlockByrefHelpers *node
2520
21
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
21
  if (node) 
return static_cast<T*>(node)8
;
2522
2523
13
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
13
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
13
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
13
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
13
  return copy;
2529
13
}
CGBlocks.cpp:(anonymous namespace)::ObjectByrefHelpers* buildByrefHelpers<(anonymous namespace)::ObjectByrefHelpers>(clang::CodeGen::CodeGenModule&, clang::CodeGen::BlockByrefInfo const&, (anonymous namespace)::ObjectByrefHelpers&&)
Line
Count
Source
2514
24
                            T &&generator) {
2515
24
  llvm::FoldingSetNodeID id;
2516
24
  generator.Profile(id);
2517
2518
24
  void *insertPos;
2519
24
  BlockByrefHelpers *node
2520
24
    = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2521
24
  if (node) 
return static_cast<T*>(node)6
;
2522
2523
18
  generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2524
18
  generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2525
2526
18
  T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2527
18
  CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2528
18
  return copy;
2529
18
}
2530
2531
/// Build the copy and dispose helpers for the given __block variable
2532
/// emission.  Places the helpers in the global cache.  Returns null
2533
/// if no helpers are required.
2534
BlockByrefHelpers *
2535
CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2536
205
                                   const AutoVarEmission &emission) {
2537
205
  const VarDecl &var = *emission.Variable;
2538
205
  assert(var.isEscapingByref() &&
2539
205
         "only escaping __block variables need byref helpers");
2540
2541
205
  QualType type = var.getType();
2542
2543
205
  auto &byrefInfo = getBlockByrefInfo(&var);
2544
2545
  // The alignment we care about for the purposes of uniquing byref
2546
  // helpers is the alignment of the actual byref value field.
2547
205
  CharUnits valueAlignment =
2548
205
    byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2549
2550
205
  if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2551
15
    const Expr *copyExpr =
2552
15
        CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2553
15
    if (!copyExpr && 
record->hasTrivialDestructor()0
)
return nullptr0
;
2554
2555
15
    return ::buildByrefHelpers(
2556
15
        CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2557
15
  }
2558
2559
  // If type is a non-trivial C struct type that is non-trivial to
2560
  // destructly move or destroy, build the copy and dispose helpers.
2561
190
  if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2562
181
      type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2563
9
    return ::buildByrefHelpers(
2564
9
        CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2565
2566
  // Otherwise, if we don't have a retainable type, there's nothing to do.
2567
  // that the runtime does extra copies.
2568
181
  if (!type->isObjCRetainableType()) 
return nullptr124
;
2569
2570
57
  Qualifiers qs = type.getQualifiers();
2571
2572
  // If we have lifetime, that dominates.
2573
57
  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2574
33
    switch (lifetime) {
2575
0
    case Qualifiers::OCL_None: llvm_unreachable("impossible");
2576
2577
    // These are just bits as far as the runtime is concerned.
2578
1
    case Qualifiers::OCL_ExplicitNone:
2579
1
    case Qualifiers::OCL_Autoreleasing:
2580
1
      return nullptr;
2581
2582
    // Tell the runtime that this is ARC __weak, called by the
2583
    // byref routines.
2584
7
    case Qualifiers::OCL_Weak:
2585
7
      return ::buildByrefHelpers(CGM, byrefInfo,
2586
7
                                 ARCWeakByrefHelpers(valueAlignment));
2587
2588
    // ARC __strong __block variables need to be retained.
2589
25
    case Qualifiers::OCL_Strong:
2590
      // Block pointers need to be copied, and there's no direct
2591
      // transfer possible.
2592
25
      if (type->isBlockPointerType()) {
2593
4
        return ::buildByrefHelpers(CGM, byrefInfo,
2594
4
                                   ARCStrongBlockByrefHelpers(valueAlignment));
2595
2596
      // Otherwise, we transfer ownership of the retain from the stack
2597
      // to the heap.
2598
21
      } else {
2599
21
        return ::buildByrefHelpers(CGM, byrefInfo,
2600
21
                                   ARCStrongByrefHelpers(valueAlignment));
2601
21
      }
2602
0
    }
2603
0
    llvm_unreachable("fell out of lifetime switch!");
2604
0
  }
2605
2606
24
  BlockFieldFlags flags;
2607
24
  if (type->isBlockPointerType()) {
2608
3
    flags |= BLOCK_FIELD_IS_BLOCK;
2609
21
  } else if (CGM.getContext().isObjCNSObjectType(type) ||
2610
21
             type->isObjCObjectPointerType()) {
2611
21
    flags |= BLOCK_FIELD_IS_OBJECT;
2612
0
  } else {
2613
0
    return nullptr;
2614
0
  }
2615
2616
24
  if (type.isObjCGCWeak())
2617
7
    flags |= BLOCK_FIELD_IS_WEAK;
2618
2619
24
  return ::buildByrefHelpers(CGM, byrefInfo,
2620
24
                             ObjectByrefHelpers(valueAlignment, flags));
2621
24
}
2622
2623
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2624
                                               const VarDecl *var,
2625
301
                                               bool followForward) {
2626
301
  auto &info = getBlockByrefInfo(var);
2627
301
  return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2628
301
}
2629
2630
Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2631
                                               const BlockByrefInfo &info,
2632
                                               bool followForward,
2633
792
                                               const llvm::Twine &name) {
2634
  // Chase the forwarding address if requested.
2635
792
  if (followForward) {
2636
363
    Address forwardingAddr = Builder.CreateStructGEP(baseAddr, 1, "forwarding");
2637
363
    baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2638
363
  }
2639
2640
792
  return Builder.CreateStructGEP(baseAddr, info.FieldIndex, name);
2641
792
}
2642
2643
/// BuildByrefInfo - This routine changes a __block variable declared as T x
2644
///   into:
2645
///
2646
///      struct {
2647
///        void *__isa;
2648
///        void *__forwarding;
2649
///        int32_t __flags;
2650
///        int32_t __size;
2651
///        void *__copy_helper;       // only if needed
2652
///        void *__destroy_helper;    // only if needed
2653
///        void *__byref_variable_layout;// only if needed
2654
///        char padding[X];           // only if needed
2655
///        T x;
2656
///      } x
2657
///
2658
1.01k
const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2659
1.01k
  auto it = BlockByrefInfos.find(D);
2660
1.01k
  if (it != BlockByrefInfos.end())
2661
556
    return it->second;
2662
2663
463
  llvm::StructType *byrefType =
2664
463
    llvm::StructType::create(getLLVMContext(),
2665
463
                             "struct.__block_byref_" + D->getNameAsString());
2666
2667
463
  QualType Ty = D->getType();
2668
2669
463
  CharUnits size;
2670
463
  SmallVector<llvm::Type *, 8> types;
2671
2672
  // void *__isa;
2673
463
  types.push_back(Int8PtrTy);
2674
463
  size += getPointerSize();
2675
2676
  // void *__forwarding;
2677
463
  types.push_back(llvm::PointerType::getUnqual(byrefType));
2678
463
  size += getPointerSize();
2679
2680
  // int32_t __flags;
2681
463
  types.push_back(Int32Ty);
2682
463
  size += CharUnits::fromQuantity(4);
2683
2684
  // int32_t __size;
2685
463
  types.push_back(Int32Ty);
2686
463
  size += CharUnits::fromQuantity(4);
2687
2688
  // Note that this must match *exactly* the logic in buildByrefHelpers.
2689
463
  bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2690
463
  if (hasCopyAndDispose) {
2691
    /// void *__copy_helper;
2692
187
    types.push_back(Int8PtrTy);
2693
187
    size += getPointerSize();
2694
2695
    /// void *__destroy_helper;
2696
187
    types.push_back(Int8PtrTy);
2697
187
    size += getPointerSize();
2698
187
  }
2699
2700
463
  bool HasByrefExtendedLayout = false;
2701
463
  Qualifiers::ObjCLifetime Lifetime;
2702
463
  if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2703
206
      HasByrefExtendedLayout) {
2704
    /// void *__byref_variable_layout;
2705
32
    types.push_back(Int8PtrTy);
2706
32
    size += CharUnits::fromQuantity(PointerSizeInBytes);
2707
32
  }
2708
2709
  // T x;
2710
463
  llvm::Type *varTy = ConvertTypeForMem(Ty);
2711
2712
463
  bool packed = false;
2713
463
  CharUnits varAlign = getContext().getDeclAlign(D);
2714
463
  CharUnits varOffset = size.alignTo(varAlign);
2715
2716
  // We may have to insert padding.
2717
463
  if (varOffset != size) {
2718
4
    llvm::Type *paddingTy =
2719
4
      llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2720
2721
4
    types.push_back(paddingTy);
2722
4
    size = varOffset;
2723
2724
  // Conversely, we might have to prevent LLVM from inserting padding.
2725
459
  } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2726
6
               > varAlign.getQuantity()) {
2727
6
    packed = true;
2728
6
  }
2729
463
  types.push_back(varTy);
2730
2731
463
  byrefType->setBody(types, packed);
2732
2733
463
  BlockByrefInfo info;
2734
463
  info.Type = byrefType;
2735
463
  info.FieldIndex = types.size() - 1;
2736
463
  info.FieldOffset = varOffset;
2737
463
  info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2738
2739
463
  auto pair = BlockByrefInfos.insert({D, info});
2740
463
  assert(pair.second && "info was inserted recursively?");
2741
463
  return pair.first->second;
2742
463
}
2743
2744
/// Initialize the structural components of a __block variable, i.e.
2745
/// everything but the actual object.
2746
205
void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2747
  // Find the address of the local.
2748
205
  Address addr = emission.Addr;
2749
2750
  // That's an alloca of the byref structure type.
2751
205
  llvm::StructType *byrefType = cast<llvm::StructType>(
2752
205
    cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2753
2754
205
  unsigned nextHeaderIndex = 0;
2755
205
  CharUnits nextHeaderOffset;
2756
205
  auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2757
995
                              const Twine &name) {
2758
995
    auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
2759
995
    Builder.CreateStore(value, fieldAddr);
2760
2761
995
    nextHeaderIndex++;
2762
995
    nextHeaderOffset += fieldSize;
2763
995
  };
2764
2765
  // Build the byref helpers if necessary.  This is null if we don't need any.
2766
205
  BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2767
2768
205
  const VarDecl &D = *emission.Variable;
2769
205
  QualType type = D.getType();
2770
2771
205
  bool HasByrefExtendedLayout;
2772
205
  Qualifiers::ObjCLifetime ByrefLifetime;
2773
205
  bool ByRefHasLifetime =
2774
205
    getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2775
2776
205
  llvm::Value *V;
2777
2778
  // Initialize the 'isa', which is just 0 or 1.
2779
205
  int isa = 0;
2780
205
  if (type.isObjCGCWeak())
2781
7
    isa = 1;
2782
205
  V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2783
205
  storeHeaderField(V, getPointerSize(), "byref.isa");
2784
2785
  // Store the address of the variable into its own forwarding pointer.
2786
205
  storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2787
2788
  // Blocks ABI:
2789
  //   c) the flags field is set to either 0 if no helper functions are
2790
  //      needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2791
205
  BlockFlags flags;
2792
205
  if (helpers) 
flags |= BLOCK_BYREF_HAS_COPY_DISPOSE80
;
2793
205
  if (ByRefHasLifetime) {
2794
82
    if (HasByrefExtendedLayout) 
flags |= BLOCK_BYREF_LAYOUT_EXTENDED15
;
2795
67
      else switch (ByrefLifetime) {
2796
25
        case Qualifiers::OCL_Strong:
2797
25
          flags |= BLOCK_BYREF_LAYOUT_STRONG;
2798
25
          break;
2799
7
        case Qualifiers::OCL_Weak:
2800
7
          flags |= BLOCK_BYREF_LAYOUT_WEAK;
2801
7
          break;
2802
13
        case Qualifiers::OCL_ExplicitNone:
2803
13
          flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2804
13
          break;
2805
22
        case Qualifiers::OCL_None:
2806
22
          if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2807
22
            flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2808
22
          break;
2809
0
        default:
2810
0
          break;
2811
82
      }
2812
82
    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2813
20
      printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2814
20
      if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2815
14
        printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2816
20
      if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2817
20
        BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2818
20
        if (ThisFlag ==  BLOCK_BYREF_LAYOUT_EXTENDED)
2819
0
          printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2820
20
        if (ThisFlag ==  BLOCK_BYREF_LAYOUT_STRONG)
2821
14
          printf(" BLOCK_BYREF_LAYOUT_STRONG");
2822
20
        if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2823
0
          printf(" BLOCK_BYREF_LAYOUT_WEAK");
2824
20
        if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2825
0
          printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2826
20
        if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2827
6
          printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2828
20
      }
2829
20
      printf("\n");
2830
20
    }
2831
82
  }
2832
205
  storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2833
205
                   getIntSize(), "byref.flags");
2834
2835
205
  CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2836
205
  V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2837
205
  storeHeaderField(V, getIntSize(), "byref.size");
2838
2839
205
  if (helpers) {
2840
80
    storeHeaderField(helpers->CopyHelper, getPointerSize(),
2841
80
                     "byref.copyHelper");
2842
80
    storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2843
80
                     "byref.disposeHelper");
2844
80
  }
2845
2846
205
  if (ByRefHasLifetime && 
HasByrefExtendedLayout82
) {
2847
15
    auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2848
15
    storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2849
15
  }
2850
205
}
2851
2852
void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2853
532
                                        bool CanThrow) {
2854
532
  llvm::FunctionCallee F = CGM.getBlockObjectDispose();
2855
532
  llvm::Value *args[] = {
2856
532
    Builder.CreateBitCast(V, Int8PtrTy),
2857
532
    llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2858
532
  };
2859
2860
532
  if (CanThrow)
2861
6
    EmitRuntimeCallOrInvoke(F, args);
2862
526
  else
2863
526
    EmitNounwindRuntimeCall(F, args);
2864
532
}
2865
2866
void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2867
                                        BlockFieldFlags Flags,
2868
515
                                        bool LoadBlockVarAddr, bool CanThrow) {
2869
515
  EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2870
515
                                        CanThrow);
2871
515
}
2872
2873
/// Adjust the declaration of something from the blocks API.
2874
static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2875
786
                                         llvm::Constant *C) {
2876
786
  auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2877
2878
786
  if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2879
149
    IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2880
149
    TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2881
149
    DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2882
2883
149
    assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2884
149
            isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2885
149
           "expected Function or GlobalVariable");
2886
2887
149
    const NamedDecl *ND = nullptr;
2888
149
    for (const auto &Result : DC->lookup(&II))
2889
18
      if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2890
18
          (ND = dyn_cast<VarDecl>(Result)))
2891
18
        break;
2892
2893
    // TODO: support static blocks runtime
2894
149
    if (GV->isDeclaration() && (!ND || 
!ND->hasAttr<DLLExportAttr>()18
)) {
2895
137
      GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2896
137
      GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2897
12
    } else {
2898
12
      GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2899
12
      GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2900
12
    }
2901
149
  }
2902
2903
786
  if (CGM.getLangOpts().BlocksRuntimeOptional && 
GV->isDeclaration()1
&&
2904
1
      GV->hasExternalLinkage())
2905
1
    GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2906
2907
786
  CGM.setDSOLocal(GV);
2908
786
}
2909
2910
532
llvm::FunctionCallee CodeGenModule::getBlockObjectDispose() {
2911
532
  if (BlockObjectDispose)
2912
386
    return BlockObjectDispose;
2913
2914
146
  llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2915
146
  llvm::FunctionType *fty
2916
146
    = llvm::FunctionType::get(VoidTy, args, false);
2917
146
  BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2918
146
  configureBlocksRuntimeObject(
2919
146
      *this, cast<llvm::Constant>(BlockObjectDispose.getCallee()));
2920
146
  return BlockObjectDispose;
2921
146
}
2922
2923
284
llvm::FunctionCallee CodeGenModule::getBlockObjectAssign() {
2924
284
  if (BlockObjectAssign)
2925
138
    return BlockObjectAssign;
2926
2927
146
  llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2928
146
  llvm::FunctionType *fty
2929
146
    = llvm::FunctionType::get(VoidTy, args, false);
2930
146
  BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2931
146
  configureBlocksRuntimeObject(
2932
146
      *this, cast<llvm::Constant>(BlockObjectAssign.getCallee()));
2933
146
  return BlockObjectAssign;
2934
146
}
2935
2936
306
llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2937
306
  if (NSConcreteGlobalBlock)
2938
149
    return NSConcreteGlobalBlock;
2939
2940
157
  NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2941
157
                                                Int8PtrTy->getPointerTo(),
2942
157
                                                nullptr);
2943
157
  configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2944
157
  return NSConcreteGlobalBlock;
2945
157
}
2946
2947
669
llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2948
669
  if (NSConcreteStackBlock)
2949
332
    return NSConcreteStackBlock;
2950
2951
337
  NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2952
337
                                               Int8PtrTy->getPointerTo(),
2953
337
                                               nullptr);
2954
337
  configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2955
337
  return NSConcreteStackBlock;
2956
337
}