Coverage Report

Created: 2022-01-18 06:27

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