Coverage Report

Created: 2021-01-23 06:44

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