Coverage Report

Created: 2021-08-24 07:12

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