1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This contains code to emit blocks.
11 //===----------------------------------------------------------------------===//
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"
32 using namespace clang
;
33 using namespace CodeGen
;
35 CGBlockInfo::CGBlockInfo(const BlockDecl
*block
, StringRef name
)
36 : Name(name
), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
37 NoEscape(false), HasCXXObject(false), UsesStret(false),
38 HasCapturedVariableLayout(false), CapturesNonExternalType(false),
39 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block
) {
41 // Skip asm prefix, if any. 'name' is usually taken directly from
42 // the mangled name of the enclosing function.
43 if (!name
.empty() && name
[0] == '\01')
44 name
= name
.substr(1);
47 // Anchor the vtable to this translation unit.
48 BlockByrefHelpers::~BlockByrefHelpers() {}
50 /// Build the given block as a global block.
51 static llvm::Constant
*buildGlobalBlock(CodeGenModule
&CGM
,
52 const CGBlockInfo
&blockInfo
,
53 llvm::Constant
*blockFn
);
55 /// Build the helper function to copy a block.
56 static llvm::Constant
*buildCopyHelper(CodeGenModule
&CGM
,
57 const CGBlockInfo
&blockInfo
) {
58 return CodeGenFunction(CGM
).GenerateCopyHelperFunction(blockInfo
);
61 /// Build the helper function to dispose of a block.
62 static llvm::Constant
*buildDisposeHelper(CodeGenModule
&CGM
,
63 const CGBlockInfo
&blockInfo
) {
64 return CodeGenFunction(CGM
).GenerateDestroyHelperFunction(blockInfo
);
69 enum class CaptureStrKind
{
70 // String for the copy helper.
72 // String for the dispose helper.
74 // Merge the strings for the copy helper and dispose helper.
78 } // end anonymous namespace
80 static std::string
getBlockCaptureStr(const CGBlockInfo::Capture
&Cap
,
81 CaptureStrKind StrKind
,
82 CharUnits BlockAlignment
,
85 static std::string
getBlockDescriptorName(const CGBlockInfo
&BlockInfo
,
87 std::string Name
= "__block_descriptor_";
88 Name
+= llvm::to_string(BlockInfo
.BlockSize
.getQuantity()) + "_";
90 if (BlockInfo
.NeedsCopyDispose
) {
91 if (CGM
.getLangOpts().Exceptions
)
93 if (CGM
.getCodeGenOpts().ObjCAutoRefCountExceptions
)
95 Name
+= llvm::to_string(BlockInfo
.BlockAlign
.getQuantity()) + "_";
97 for (auto &Cap
: BlockInfo
.SortedCaptures
) {
98 if (Cap
.isConstantOrTrivial())
101 Name
+= llvm::to_string(Cap
.getOffset().getQuantity());
103 if (Cap
.CopyKind
== Cap
.DisposeKind
) {
104 // If CopyKind and DisposeKind are the same, merge the capture
106 assert(Cap
.CopyKind
!= BlockCaptureEntityKind::None
&&
107 "shouldn't see BlockCaptureManagedEntity that is None");
108 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::Merged
,
109 BlockInfo
.BlockAlign
, CGM
);
111 // If CopyKind and DisposeKind are not the same, which can happen when
112 // either Kind is None or the captured object is a __strong block,
113 // concatenate the copy and dispose strings.
114 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::CopyHelper
,
115 BlockInfo
.BlockAlign
, CGM
);
116 Name
+= getBlockCaptureStr(Cap
, CaptureStrKind::DisposeHelper
,
117 BlockInfo
.BlockAlign
, CGM
);
123 std::string TypeAtEncoding
=
124 CGM
.getContext().getObjCEncodingForBlock(BlockInfo
.getBlockExpr());
125 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
126 /// a separator between symbol name and symbol version.
127 std::replace(TypeAtEncoding
.begin(), TypeAtEncoding
.end(), '@', '\1');
128 Name
+= "e" + llvm::to_string(TypeAtEncoding
.size()) + "_" + TypeAtEncoding
;
129 Name
+= "l" + CGM
.getObjCRuntime().getRCBlockLayoutStr(CGM
, BlockInfo
);
133 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
134 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
135 /// meta-data and contains stationary information about the block literal.
136 /// Its definition will have 4 (or optionally 6) words.
138 /// struct Block_descriptor {
139 /// unsigned long reserved;
140 /// unsigned long size; // size of Block_literal metadata in bytes.
141 /// void *copy_func_helper_decl; // optional copy helper.
142 /// void *destroy_func_decl; // optional destructor helper.
143 /// void *block_method_encoding_address; // @encode for block literal signature.
144 /// void *block_layout_info; // encoding of captured block variables.
147 static llvm::Constant
*buildBlockDescriptor(CodeGenModule
&CGM
,
148 const CGBlockInfo
&blockInfo
) {
149 ASTContext
&C
= CGM
.getContext();
151 llvm::IntegerType
*ulong
=
152 cast
<llvm::IntegerType
>(CGM
.getTypes().ConvertType(C
.UnsignedLongTy
));
153 llvm::PointerType
*i8p
= nullptr;
154 if (CGM
.getLangOpts().OpenCL
)
155 i8p
= llvm::PointerType::get(
156 CGM
.getLLVMContext(), C
.getTargetAddressSpace(LangAS::opencl_constant
));
160 std::string descName
;
162 // If an equivalent block descriptor global variable exists, return it.
163 if (C
.getLangOpts().ObjC
&&
164 CGM
.getLangOpts().getGC() == LangOptions::NonGC
) {
165 descName
= getBlockDescriptorName(blockInfo
, CGM
);
166 if (llvm::GlobalValue
*desc
= CGM
.getModule().getNamedValue(descName
))
167 return llvm::ConstantExpr::getBitCast(desc
,
168 CGM
.getBlockDescriptorType());
171 // If there isn't an equivalent block descriptor global variable, create a new
173 ConstantInitBuilder
builder(CGM
);
174 auto elements
= builder
.beginStruct();
177 elements
.addInt(ulong
, 0);
180 // FIXME: What is the right way to say this doesn't fit? We should give
181 // a user diagnostic in that case. Better fix would be to change the
183 elements
.addInt(ulong
, blockInfo
.BlockSize
.getQuantity());
185 // Optional copy/dispose helpers.
186 bool hasInternalHelper
= false;
187 if (blockInfo
.NeedsCopyDispose
) {
188 // copy_func_helper_decl
189 llvm::Constant
*copyHelper
= buildCopyHelper(CGM
, blockInfo
);
190 elements
.add(copyHelper
);
193 llvm::Constant
*disposeHelper
= buildDisposeHelper(CGM
, blockInfo
);
194 elements
.add(disposeHelper
);
196 if (cast
<llvm::Function
>(copyHelper
->stripPointerCasts())
197 ->hasInternalLinkage() ||
198 cast
<llvm::Function
>(disposeHelper
->stripPointerCasts())
199 ->hasInternalLinkage())
200 hasInternalHelper
= true;
203 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
204 std::string typeAtEncoding
=
205 CGM
.getContext().getObjCEncodingForBlock(blockInfo
.getBlockExpr());
206 elements
.add(llvm::ConstantExpr::getBitCast(
207 CGM
.GetAddrOfConstantCString(typeAtEncoding
).getPointer(), i8p
));
210 if (C
.getLangOpts().ObjC
) {
211 if (CGM
.getLangOpts().getGC() != LangOptions::NonGC
)
212 elements
.add(CGM
.getObjCRuntime().BuildGCBlockLayout(CGM
, blockInfo
));
214 elements
.add(CGM
.getObjCRuntime().BuildRCBlockLayout(CGM
, blockInfo
));
217 elements
.addNullPointer(i8p
);
219 unsigned AddrSpace
= 0;
220 if (C
.getLangOpts().OpenCL
)
221 AddrSpace
= C
.getTargetAddressSpace(LangAS::opencl_constant
);
223 llvm::GlobalValue::LinkageTypes linkage
;
224 if (descName
.empty()) {
225 linkage
= llvm::GlobalValue::InternalLinkage
;
226 descName
= "__block_descriptor_tmp";
227 } else if (hasInternalHelper
) {
228 // If either the copy helper or the dispose helper has internal linkage,
229 // the block descriptor must have internal linkage too.
230 linkage
= llvm::GlobalValue::InternalLinkage
;
232 linkage
= llvm::GlobalValue::LinkOnceODRLinkage
;
235 llvm::GlobalVariable
*global
=
236 elements
.finishAndCreateGlobal(descName
, CGM
.getPointerAlign(),
237 /*constant*/ true, linkage
, AddrSpace
);
239 if (linkage
== llvm::GlobalValue::LinkOnceODRLinkage
) {
240 if (CGM
.supportsCOMDAT())
241 global
->setComdat(CGM
.getModule().getOrInsertComdat(descName
));
242 global
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
243 global
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
246 return llvm::ConstantExpr::getBitCast(global
, CGM
.getBlockDescriptorType());
250 Purely notional variadic template describing the layout of a block.
252 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
253 struct Block_literal {
254 /// Initialized to one of:
255 /// extern void *_NSConcreteStackBlock[];
256 /// extern void *_NSConcreteGlobalBlock[];
258 /// In theory, we could start one off malloc'ed by setting
259 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
261 /// extern void *_NSConcreteMallocBlock[];
262 struct objc_class *isa;
264 /// These are the flags (with corresponding bit number) that the
265 /// compiler is actually supposed to know about.
266 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
267 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
268 /// descriptor provides copy and dispose helper functions
269 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
270 /// object with a nontrivial destructor or copy constructor
271 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
273 /// 29. BLOCK_USE_STRET - indicates that the block function
274 /// uses stret, which objc_msgSend needs to know about
275 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
276 /// @encoded signature string
277 /// And we're not supposed to manipulate these:
278 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
279 /// to malloc'ed memory
280 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
281 /// to GC-allocated memory
282 /// Additionally, the bottom 16 bits are a reference count which
283 /// should be zero on the stack.
286 /// Reserved; should be zero-initialized.
289 /// Function pointer generated from block literal.
290 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
292 /// Block description metadata generated from block literal.
293 struct Block_descriptor *block_descriptor;
295 /// Captured values follow.
296 _CapturesTypes captures...;
301 /// A chunk of data that we actually have to capture in the block.
302 struct BlockLayoutChunk
{
305 const BlockDecl::Capture
*Capture
; // null for 'this'
308 BlockCaptureEntityKind CopyKind
, DisposeKind
;
309 BlockFieldFlags CopyFlags
, DisposeFlags
;
311 BlockLayoutChunk(CharUnits align
, CharUnits size
,
312 const BlockDecl::Capture
*capture
, llvm::Type
*type
,
313 QualType fieldType
, BlockCaptureEntityKind CopyKind
,
314 BlockFieldFlags CopyFlags
,
315 BlockCaptureEntityKind DisposeKind
,
316 BlockFieldFlags DisposeFlags
)
317 : Alignment(align
), Size(size
), Capture(capture
), Type(type
),
318 FieldType(fieldType
), CopyKind(CopyKind
), DisposeKind(DisposeKind
),
319 CopyFlags(CopyFlags
), DisposeFlags(DisposeFlags
) {}
321 /// Tell the block info that this chunk has the given field index.
322 void setIndex(CGBlockInfo
&info
, unsigned index
, CharUnits offset
) {
324 info
.CXXThisIndex
= index
;
325 info
.CXXThisOffset
= offset
;
327 info
.SortedCaptures
.push_back(CGBlockInfo::Capture::makeIndex(
328 index
, offset
, FieldType
, CopyKind
, CopyFlags
, DisposeKind
,
329 DisposeFlags
, Capture
));
333 bool isTrivial() const {
334 return CopyKind
== BlockCaptureEntityKind::None
&&
335 DisposeKind
== BlockCaptureEntityKind::None
;
339 /// Order by 1) all __strong together 2) next, all block together 3) next,
340 /// all byref together 4) next, all __weak together. Preserve descending
341 /// alignment in all situations.
342 bool operator<(const BlockLayoutChunk
&left
, const BlockLayoutChunk
&right
) {
343 if (left
.Alignment
!= right
.Alignment
)
344 return left
.Alignment
> right
.Alignment
;
346 auto getPrefOrder
= [](const BlockLayoutChunk
&chunk
) {
347 switch (chunk
.CopyKind
) {
348 case BlockCaptureEntityKind::ARCStrong
:
350 case BlockCaptureEntityKind::BlockObject
:
351 switch (chunk
.CopyFlags
.getBitMask()) {
352 case BLOCK_FIELD_IS_OBJECT
:
354 case BLOCK_FIELD_IS_BLOCK
:
356 case BLOCK_FIELD_IS_BYREF
:
362 case BlockCaptureEntityKind::ARCWeak
:
370 return getPrefOrder(left
) < getPrefOrder(right
);
372 } // end anonymous namespace
374 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
375 computeCopyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
376 const LangOptions
&LangOpts
);
378 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
379 computeDestroyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
380 const LangOptions
&LangOpts
);
382 static void addBlockLayout(CharUnits align
, CharUnits size
,
383 const BlockDecl::Capture
*capture
, llvm::Type
*type
,
385 SmallVectorImpl
<BlockLayoutChunk
> &Layout
,
386 CGBlockInfo
&Info
, CodeGenModule
&CGM
) {
389 Layout
.push_back(BlockLayoutChunk(
390 align
, size
, capture
, type
, fieldType
, BlockCaptureEntityKind::None
,
391 BlockFieldFlags(), BlockCaptureEntityKind::None
, BlockFieldFlags()));
395 const LangOptions
&LangOpts
= CGM
.getLangOpts();
396 BlockCaptureEntityKind CopyKind
, DisposeKind
;
397 BlockFieldFlags CopyFlags
, DisposeFlags
;
399 std::tie(CopyKind
, CopyFlags
) =
400 computeCopyInfoForBlockCapture(*capture
, fieldType
, LangOpts
);
401 std::tie(DisposeKind
, DisposeFlags
) =
402 computeDestroyInfoForBlockCapture(*capture
, fieldType
, LangOpts
);
403 Layout
.push_back(BlockLayoutChunk(align
, size
, capture
, type
, fieldType
,
404 CopyKind
, CopyFlags
, DisposeKind
,
410 if (!Layout
.back().isTrivial())
411 Info
.NeedsCopyDispose
= true;
414 /// Determines if the given type is safe for constant capture in C++.
415 static bool isSafeForCXXConstantCapture(QualType type
) {
416 const RecordType
*recordType
=
417 type
->getBaseElementTypeUnsafe()->getAs
<RecordType
>();
419 // Only records can be unsafe.
420 if (!recordType
) return true;
422 const auto *record
= cast
<CXXRecordDecl
>(recordType
->getDecl());
424 // Maintain semantics for classes with non-trivial dtors or copy ctors.
425 if (!record
->hasTrivialDestructor()) return false;
426 if (record
->hasNonTrivialCopyConstructor()) return false;
428 // Otherwise, we just have to make sure there aren't any mutable
429 // fields that might have changed since initialization.
430 return !record
->hasMutableFields();
433 /// It is illegal to modify a const object after initialization.
434 /// Therefore, if a const object has a constant initializer, we don't
435 /// actually need to keep storage for it in the block; we'll just
436 /// rematerialize it at the start of the block function. This is
437 /// acceptable because we make no promises about address stability of
438 /// captured variables.
439 static llvm::Constant
*tryCaptureAsConstant(CodeGenModule
&CGM
,
440 CodeGenFunction
*CGF
,
441 const VarDecl
*var
) {
442 // Return if this is a function parameter. We shouldn't try to
443 // rematerialize default arguments of function parameters.
444 if (isa
<ParmVarDecl
>(var
))
447 QualType type
= var
->getType();
449 // We can only do this if the variable is const.
450 if (!type
.isConstQualified()) return nullptr;
452 // Furthermore, in C++ we have to worry about mutable fields:
453 // C++ [dcl.type.cv]p4:
454 // Except that any class member declared mutable can be
455 // modified, any attempt to modify a const object during its
456 // lifetime results in undefined behavior.
457 if (CGM
.getLangOpts().CPlusPlus
&& !isSafeForCXXConstantCapture(type
))
460 // If the variable doesn't have any initializer (shouldn't this be
461 // invalid?), it's not clear what we should do. Maybe capture as
463 const Expr
*init
= var
->getInit();
464 if (!init
) return nullptr;
466 return ConstantEmitter(CGM
, CGF
).tryEmitAbstractForInitializer(*var
);
469 /// Get the low bit of a nonzero character count. This is the
470 /// alignment of the nth byte if the 0th byte is universally aligned.
471 static CharUnits
getLowBit(CharUnits v
) {
472 return CharUnits::fromQuantity(v
.getQuantity() & (~v
.getQuantity() + 1));
475 static void initializeForBlockHeader(CodeGenModule
&CGM
, CGBlockInfo
&info
,
476 SmallVectorImpl
<llvm::Type
*> &elementTypes
) {
478 assert(elementTypes
.empty());
479 if (CGM
.getLangOpts().OpenCL
) {
480 // The header is basically 'struct { int; int; generic void *;
481 // custom_fields; }'. Assert that struct is packed.
482 auto GenPtrAlign
= CharUnits::fromQuantity(
483 CGM
.getTarget().getPointerAlign(LangAS::opencl_generic
) / 8);
484 auto GenPtrSize
= CharUnits::fromQuantity(
485 CGM
.getTarget().getPointerWidth(LangAS::opencl_generic
) / 8);
486 assert(CGM
.getIntSize() <= GenPtrSize
);
487 assert(CGM
.getIntAlign() <= GenPtrAlign
);
488 assert((2 * CGM
.getIntSize()).isMultipleOf(GenPtrAlign
));
489 elementTypes
.push_back(CGM
.IntTy
); /* total size */
490 elementTypes
.push_back(CGM
.IntTy
); /* align */
491 elementTypes
.push_back(
492 CGM
.getOpenCLRuntime()
493 .getGenericVoidPointerType()); /* invoke function */
495 2 * CGM
.getIntSize().getQuantity() + GenPtrSize
.getQuantity();
496 unsigned BlockAlign
= GenPtrAlign
.getQuantity();
498 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
499 for (auto *I
: Helper
->getCustomFieldTypes()) /* custom fields */ {
500 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
501 // If necessary, add padding fields to the custom fields.
502 unsigned Align
= CGM
.getDataLayout().getABITypeAlign(I
).value();
503 if (BlockAlign
< Align
)
505 assert(Offset
% Align
== 0);
506 Offset
+= CGM
.getDataLayout().getTypeAllocSize(I
);
507 elementTypes
.push_back(I
);
510 info
.BlockAlign
= CharUnits::fromQuantity(BlockAlign
);
511 info
.BlockSize
= CharUnits::fromQuantity(Offset
);
513 // The header is basically 'struct { void *; int; int; void *; void *; }'.
514 // Assert that the struct is packed.
515 assert(CGM
.getIntSize() <= CGM
.getPointerSize());
516 assert(CGM
.getIntAlign() <= CGM
.getPointerAlign());
517 assert((2 * CGM
.getIntSize()).isMultipleOf(CGM
.getPointerAlign()));
518 info
.BlockAlign
= CGM
.getPointerAlign();
519 info
.BlockSize
= 3 * CGM
.getPointerSize() + 2 * CGM
.getIntSize();
520 elementTypes
.push_back(CGM
.VoidPtrTy
);
521 elementTypes
.push_back(CGM
.IntTy
);
522 elementTypes
.push_back(CGM
.IntTy
);
523 elementTypes
.push_back(CGM
.VoidPtrTy
);
524 elementTypes
.push_back(CGM
.getBlockDescriptorType());
528 static QualType
getCaptureFieldType(const CodeGenFunction
&CGF
,
529 const BlockDecl::Capture
&CI
) {
530 const VarDecl
*VD
= CI
.getVariable();
532 // If the variable is captured by an enclosing block or lambda expression,
533 // use the type of the capture field.
534 if (CGF
.BlockInfo
&& CI
.isNested())
535 return CGF
.BlockInfo
->getCapture(VD
).fieldType();
536 if (auto *FD
= CGF
.LambdaCaptureFields
.lookup(VD
))
537 return FD
->getType();
538 // If the captured variable is a non-escaping __block variable, the field
539 // type is the reference type. If the variable is a __block variable that
540 // already has a reference type, the field type is the variable's type.
541 return VD
->isNonEscapingByref() ?
542 CGF
.getContext().getLValueReferenceType(VD
->getType()) : VD
->getType();
545 /// Compute the layout of the given block. Attempts to lay the block
546 /// out with minimal space requirements.
547 static void computeBlockInfo(CodeGenModule
&CGM
, CodeGenFunction
*CGF
,
549 ASTContext
&C
= CGM
.getContext();
550 const BlockDecl
*block
= info
.getBlockDecl();
552 SmallVector
<llvm::Type
*, 8> elementTypes
;
553 initializeForBlockHeader(CGM
, info
, elementTypes
);
554 bool hasNonConstantCustomFields
= false;
555 if (auto *OpenCLHelper
=
556 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
557 hasNonConstantCustomFields
=
558 !OpenCLHelper
->areAllCustomFieldValuesConstant(info
);
559 if (!block
->hasCaptures() && !hasNonConstantCustomFields
) {
561 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
562 info
.CanBeGlobal
= true;
565 else if (C
.getLangOpts().ObjC
&&
566 CGM
.getLangOpts().getGC() == LangOptions::NonGC
)
567 info
.HasCapturedVariableLayout
= true;
569 if (block
->doesNotEscape())
570 info
.NoEscape
= true;
572 // Collect the layout chunks.
573 SmallVector
<BlockLayoutChunk
, 16> layout
;
574 layout
.reserve(block
->capturesCXXThis() +
575 (block
->capture_end() - block
->capture_begin()));
577 CharUnits maxFieldAlign
;
580 if (block
->capturesCXXThis()) {
581 assert(CGF
&& CGF
->CurFuncDecl
&& isa
<CXXMethodDecl
>(CGF
->CurFuncDecl
) &&
582 "Can't capture 'this' outside a method");
583 QualType thisType
= cast
<CXXMethodDecl
>(CGF
->CurFuncDecl
)->getThisType();
585 // Theoretically, this could be in a different address space, so
586 // don't assume standard pointer size/align.
587 llvm::Type
*llvmType
= CGM
.getTypes().ConvertType(thisType
);
588 auto TInfo
= CGM
.getContext().getTypeInfoInChars(thisType
);
589 maxFieldAlign
= std::max(maxFieldAlign
, TInfo
.Align
);
591 addBlockLayout(TInfo
.Align
, TInfo
.Width
, nullptr, llvmType
, thisType
,
595 // Next, all the block captures.
596 for (const auto &CI
: block
->captures()) {
597 const VarDecl
*variable
= CI
.getVariable();
599 if (CI
.isEscapingByref()) {
600 // Just use void* instead of a pointer to the byref type.
601 CharUnits align
= CGM
.getPointerAlign();
602 maxFieldAlign
= std::max(maxFieldAlign
, align
);
604 // Since a __block variable cannot be captured by lambdas, its type and
605 // the capture field type should always match.
606 assert(CGF
&& getCaptureFieldType(*CGF
, CI
) == variable
->getType() &&
607 "capture type differs from the variable type");
608 addBlockLayout(align
, CGM
.getPointerSize(), &CI
, CGM
.VoidPtrTy
,
609 variable
->getType(), layout
, info
, CGM
);
613 // Otherwise, build a layout chunk with the size and alignment of
615 if (llvm::Constant
*constant
= tryCaptureAsConstant(CGM
, CGF
, variable
)) {
616 info
.SortedCaptures
.push_back(
617 CGBlockInfo::Capture::makeConstant(constant
, &CI
));
621 QualType VT
= getCaptureFieldType(*CGF
, CI
);
623 if (CGM
.getLangOpts().CPlusPlus
)
624 if (const CXXRecordDecl
*record
= VT
->getAsCXXRecordDecl())
625 if (CI
.hasCopyExpr() || !record
->hasTrivialDestructor()) {
626 info
.HasCXXObject
= true;
627 if (!record
->isExternallyVisible())
628 info
.CapturesNonExternalType
= true;
631 CharUnits size
= C
.getTypeSizeInChars(VT
);
632 CharUnits align
= C
.getDeclAlign(variable
);
634 maxFieldAlign
= std::max(maxFieldAlign
, align
);
636 llvm::Type
*llvmType
=
637 CGM
.getTypes().ConvertTypeForMem(VT
);
639 addBlockLayout(align
, size
, &CI
, llvmType
, VT
, layout
, info
, CGM
);
642 // If that was everything, we're done here.
643 if (layout
.empty()) {
645 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
646 info
.CanBeGlobal
= true;
647 info
.buildCaptureMap();
651 // Sort the layout by alignment. We have to use a stable sort here
652 // to get reproducible results. There should probably be an
653 // llvm::array_pod_stable_sort.
654 llvm::stable_sort(layout
);
656 // Needed for blocks layout info.
657 info
.BlockHeaderForcedGapOffset
= info
.BlockSize
;
658 info
.BlockHeaderForcedGapSize
= CharUnits::Zero();
660 CharUnits
&blockSize
= info
.BlockSize
;
661 info
.BlockAlign
= std::max(maxFieldAlign
, info
.BlockAlign
);
663 // Assuming that the first byte in the header is maximally aligned,
664 // get the alignment of the first byte following the header.
665 CharUnits endAlign
= getLowBit(blockSize
);
667 // If the end of the header isn't satisfactorily aligned for the
668 // maximum thing, look for things that are okay with the header-end
669 // alignment, and keep appending them until we get something that's
670 // aligned right. This algorithm is only guaranteed optimal if
671 // that condition is satisfied at some point; otherwise we can get
673 // header // next byte has alignment 4
674 // something_with_size_5; // next byte has alignment 1
675 // something_with_alignment_8;
676 // which has 7 bytes of padding, as opposed to the naive solution
677 // which might have less (?).
678 if (endAlign
< maxFieldAlign
) {
679 SmallVectorImpl
<BlockLayoutChunk
>::iterator
680 li
= layout
.begin() + 1, le
= layout
.end();
682 // Look for something that the header end is already
683 // satisfactorily aligned for.
684 for (; li
!= le
&& endAlign
< li
->Alignment
; ++li
)
687 // If we found something that's naturally aligned for the end of
688 // the header, keep adding things...
690 SmallVectorImpl
<BlockLayoutChunk
>::iterator first
= li
;
691 for (; li
!= le
; ++li
) {
692 assert(endAlign
>= li
->Alignment
);
694 li
->setIndex(info
, elementTypes
.size(), blockSize
);
695 elementTypes
.push_back(li
->Type
);
696 blockSize
+= li
->Size
;
697 endAlign
= getLowBit(blockSize
);
699 // ...until we get to the alignment of the maximum field.
700 if (endAlign
>= maxFieldAlign
) {
705 // Don't re-append everything we just appended.
706 layout
.erase(first
, li
);
710 assert(endAlign
== getLowBit(blockSize
));
712 // At this point, we just have to add padding if the end align still
713 // isn't aligned right.
714 if (endAlign
< maxFieldAlign
) {
715 CharUnits newBlockSize
= blockSize
.alignTo(maxFieldAlign
);
716 CharUnits padding
= newBlockSize
- blockSize
;
718 // If we haven't yet added any fields, remember that there was an
719 // initial gap; this need to go into the block layout bit map.
720 if (blockSize
== info
.BlockHeaderForcedGapOffset
) {
721 info
.BlockHeaderForcedGapSize
= padding
;
724 elementTypes
.push_back(llvm::ArrayType::get(CGM
.Int8Ty
,
725 padding
.getQuantity()));
726 blockSize
= newBlockSize
;
727 endAlign
= getLowBit(blockSize
); // might be > maxFieldAlign
730 assert(endAlign
>= maxFieldAlign
);
731 assert(endAlign
== getLowBit(blockSize
));
732 // Slam everything else on now. This works because they have
733 // strictly decreasing alignment and we expect that size is always a
734 // multiple of alignment.
735 for (SmallVectorImpl
<BlockLayoutChunk
>::iterator
736 li
= layout
.begin(), le
= layout
.end(); li
!= le
; ++li
) {
737 if (endAlign
< li
->Alignment
) {
738 // size may not be multiple of alignment. This can only happen with
739 // an over-aligned variable. We will be adding a padding field to
740 // make the size be multiple of alignment.
741 CharUnits padding
= li
->Alignment
- endAlign
;
742 elementTypes
.push_back(llvm::ArrayType::get(CGM
.Int8Ty
,
743 padding
.getQuantity()));
744 blockSize
+= padding
;
745 endAlign
= getLowBit(blockSize
);
747 assert(endAlign
>= li
->Alignment
);
748 li
->setIndex(info
, elementTypes
.size(), blockSize
);
749 elementTypes
.push_back(li
->Type
);
750 blockSize
+= li
->Size
;
751 endAlign
= getLowBit(blockSize
);
754 info
.buildCaptureMap();
756 llvm::StructType::get(CGM
.getLLVMContext(), elementTypes
, true);
759 /// Emit a block literal expression in the current function.
760 llvm::Value
*CodeGenFunction::EmitBlockLiteral(const BlockExpr
*blockExpr
) {
761 // If the block has no captures, we won't have a pre-computed
763 if (!blockExpr
->getBlockDecl()->hasCaptures())
764 // The block literal is emitted as a global variable, and the block invoke
765 // function has to be extracted from its initializer.
766 if (llvm::Constant
*Block
= CGM
.getAddrOfGlobalBlockIfEmitted(blockExpr
))
769 CGBlockInfo
blockInfo(blockExpr
->getBlockDecl(), CurFn
->getName());
770 computeBlockInfo(CGM
, this, blockInfo
);
771 blockInfo
.BlockExpression
= blockExpr
;
772 if (!blockInfo
.CanBeGlobal
)
773 blockInfo
.LocalAddress
= CreateTempAlloca(blockInfo
.StructureType
,
774 blockInfo
.BlockAlign
, "block");
775 return EmitBlockLiteral(blockInfo
);
778 llvm::Value
*CodeGenFunction::EmitBlockLiteral(const CGBlockInfo
&blockInfo
) {
779 bool IsOpenCL
= CGM
.getContext().getLangOpts().OpenCL
;
781 IsOpenCL
? CGM
.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy
;
782 LangAS GenVoidPtrAddr
= IsOpenCL
? LangAS::opencl_generic
: LangAS::Default
;
783 auto GenVoidPtrSize
= CharUnits::fromQuantity(
784 CGM
.getTarget().getPointerWidth(GenVoidPtrAddr
) / 8);
785 // Using the computed layout, generate the actual block function.
786 bool isLambdaConv
= blockInfo
.getBlockDecl()->isConversionFromLambda();
787 CodeGenFunction BlockCGF
{CGM
, true};
788 BlockCGF
.SanOpts
= SanOpts
;
789 auto *InvokeFn
= BlockCGF
.GenerateBlockFunction(
790 CurGD
, blockInfo
, LocalDeclMap
, isLambdaConv
, blockInfo
.CanBeGlobal
);
791 auto *blockFn
= llvm::ConstantExpr::getPointerCast(InvokeFn
, GenVoidPtrTy
);
793 // If there is nothing to capture, we can emit this as a global block.
794 if (blockInfo
.CanBeGlobal
)
795 return CGM
.getAddrOfGlobalBlockIfEmitted(blockInfo
.BlockExpression
);
797 // Otherwise, we have to emit this as a local block.
799 Address blockAddr
= blockInfo
.LocalAddress
;
800 assert(blockAddr
.isValid() && "block has no address!");
803 llvm::Constant
*descriptor
;
806 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
807 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
808 // block just returns the original block and releasing it is a no-op.
809 llvm::Constant
*blockISA
= blockInfo
.NoEscape
810 ? CGM
.getNSConcreteGlobalBlock()
811 : CGM
.getNSConcreteStackBlock();
812 isa
= llvm::ConstantExpr::getBitCast(blockISA
, VoidPtrTy
);
814 // Build the block descriptor.
815 descriptor
= buildBlockDescriptor(CGM
, blockInfo
);
817 // Compute the initial on-stack block flags.
818 flags
= BLOCK_HAS_SIGNATURE
;
819 if (blockInfo
.HasCapturedVariableLayout
)
820 flags
|= BLOCK_HAS_EXTENDED_LAYOUT
;
821 if (blockInfo
.NeedsCopyDispose
)
822 flags
|= BLOCK_HAS_COPY_DISPOSE
;
823 if (blockInfo
.HasCXXObject
)
824 flags
|= BLOCK_HAS_CXX_OBJ
;
825 if (blockInfo
.UsesStret
)
826 flags
|= BLOCK_USE_STRET
;
827 if (blockInfo
.NoEscape
)
828 flags
|= BLOCK_IS_NOESCAPE
| BLOCK_IS_GLOBAL
;
831 auto projectField
= [&](unsigned index
, const Twine
&name
) -> Address
{
832 return Builder
.CreateStructGEP(blockAddr
, index
, name
);
834 auto storeField
= [&](llvm::Value
*value
, unsigned index
, const Twine
&name
) {
835 Builder
.CreateStore(value
, projectField(index
, name
));
838 // Initialize the block header.
840 // We assume all the header fields are densely packed.
843 auto addHeaderField
= [&](llvm::Value
*value
, CharUnits size
,
845 storeField(value
, index
, name
);
851 addHeaderField(isa
, getPointerSize(), "block.isa");
852 addHeaderField(llvm::ConstantInt::get(IntTy
, flags
.getBitMask()),
853 getIntSize(), "block.flags");
854 addHeaderField(llvm::ConstantInt::get(IntTy
, 0), getIntSize(),
858 llvm::ConstantInt::get(IntTy
, blockInfo
.BlockSize
.getQuantity()),
859 getIntSize(), "block.size");
861 llvm::ConstantInt::get(IntTy
, blockInfo
.BlockAlign
.getQuantity()),
862 getIntSize(), "block.align");
864 addHeaderField(blockFn
, GenVoidPtrSize
, "block.invoke");
866 addHeaderField(descriptor
, getPointerSize(), "block.descriptor");
867 else if (auto *Helper
=
868 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
869 for (auto I
: Helper
->getCustomFieldValues(*this, blockInfo
)) {
872 CharUnits::fromQuantity(
873 CGM
.getDataLayout().getTypeAllocSize(I
.first
->getType())),
879 // Finally, capture all the values into the block.
880 const BlockDecl
*blockDecl
= blockInfo
.getBlockDecl();
883 if (blockDecl
->capturesCXXThis()) {
885 projectField(blockInfo
.CXXThisIndex
, "block.captured-this.addr");
886 Builder
.CreateStore(LoadCXXThis(), addr
);
889 // Next, captured variables.
890 for (const auto &CI
: blockDecl
->captures()) {
891 const VarDecl
*variable
= CI
.getVariable();
892 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
894 // Ignore constant captures.
895 if (capture
.isConstant()) continue;
897 QualType type
= capture
.fieldType();
899 // This will be a [[type]]*, except that a byref entry will just be
901 Address blockField
= projectField(capture
.getIndex(), "block.captured");
903 // Compute the address of the thing we're going to move into the
905 Address src
= Address::invalid();
907 if (blockDecl
->isConversionFromLambda()) {
908 // The lambda capture in a lambda's conversion-to-block-pointer is
909 // special; we'll simply emit it directly.
910 src
= Address::invalid();
911 } else if (CI
.isEscapingByref()) {
912 if (BlockInfo
&& CI
.isNested()) {
913 // We need to use the capture from the enclosing block.
914 const CGBlockInfo::Capture
&enclosingCapture
=
915 BlockInfo
->getCapture(variable
);
917 // This is a [[type]]*, except that a byref entry will just be an i8**.
918 src
= Builder
.CreateStructGEP(LoadBlockStruct(),
919 enclosingCapture
.getIndex(),
920 "block.capture.addr");
922 auto I
= LocalDeclMap
.find(variable
);
923 assert(I
!= LocalDeclMap
.end());
927 DeclRefExpr
declRef(getContext(), const_cast<VarDecl
*>(variable
),
928 /*RefersToEnclosingVariableOrCapture*/ CI
.isNested(),
929 type
.getNonReferenceType(), VK_LValue
,
931 src
= EmitDeclRefLValue(&declRef
).getAddress(*this);
934 // For byrefs, we just write the pointer to the byref struct into
935 // the block field. There's no need to chase the forwarding
936 // pointer at this point, since we're building something that will
937 // live a shorter life than the stack byref anyway.
938 if (CI
.isEscapingByref()) {
939 // Get a void* that points to the byref struct.
940 llvm::Value
*byrefPointer
;
942 byrefPointer
= Builder
.CreateLoad(src
, "byref.capture");
944 byrefPointer
= src
.getPointer();
946 // Write that void* into the capture field.
947 Builder
.CreateStore(byrefPointer
, blockField
);
949 // If we have a copy constructor, evaluate that into the block field.
950 } else if (const Expr
*copyExpr
= CI
.getCopyExpr()) {
951 if (blockDecl
->isConversionFromLambda()) {
952 // If we have a lambda conversion, emit the expression
953 // directly into the block instead.
955 AggValueSlot::forAddr(blockField
, Qualifiers(),
956 AggValueSlot::IsDestructed
,
957 AggValueSlot::DoesNotNeedGCBarriers
,
958 AggValueSlot::IsNotAliased
,
959 AggValueSlot::DoesNotOverlap
);
960 EmitAggExpr(copyExpr
, Slot
);
962 EmitSynthesizedCXXCopyCtor(blockField
, src
, copyExpr
);
965 // If it's a reference variable, copy the reference into the block field.
966 } else if (type
->isReferenceType()) {
967 Builder
.CreateStore(src
.getPointer(), blockField
);
969 // If type is const-qualified, copy the value into the block field.
970 } else if (type
.isConstQualified() &&
971 type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
972 CGM
.getCodeGenOpts().OptimizationLevel
!= 0) {
973 llvm::Value
*value
= Builder
.CreateLoad(src
, "captured");
974 Builder
.CreateStore(value
, blockField
);
976 // If this is an ARC __strong block-pointer variable, don't do a
979 // TODO: this can be generalized into the normal initialization logic:
980 // we should never need to do a block-copy when initializing a local
981 // variable, because the local variable's lifetime should be strictly
982 // contained within the stack block's.
983 } else if (type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
984 type
->isBlockPointerType()) {
985 // Load the block and do a simple retain.
986 llvm::Value
*value
= Builder
.CreateLoad(src
, "block.captured_block");
987 value
= EmitARCRetainNonBlock(value
);
989 // Do a primitive store to the block field.
990 Builder
.CreateStore(value
, blockField
);
992 // Otherwise, fake up a POD copy into the block field.
994 // Fake up a new variable so that EmitScalarInit doesn't think
995 // we're referring to the variable in its own initializer.
996 ImplicitParamDecl
BlockFieldPseudoVar(getContext(), type
,
997 ImplicitParamDecl::Other
);
999 // We use one of these or the other depending on whether the
1000 // reference is nested.
1001 DeclRefExpr
declRef(getContext(), const_cast<VarDecl
*>(variable
),
1002 /*RefersToEnclosingVariableOrCapture*/ CI
.isNested(),
1003 type
, VK_LValue
, SourceLocation());
1005 ImplicitCastExpr
l2r(ImplicitCastExpr::OnStack
, type
, CK_LValueToRValue
,
1006 &declRef
, VK_PRValue
, FPOptionsOverride());
1007 // FIXME: Pass a specific location for the expr init so that the store is
1008 // attributed to a reasonable location - otherwise it may be attributed to
1009 // locations of subexpressions in the initialization.
1010 EmitExprAsInit(&l2r
, &BlockFieldPseudoVar
,
1011 MakeAddrLValue(blockField
, type
, AlignmentSource::Decl
),
1012 /*captured by init*/ false);
1015 // Push a cleanup for the capture if necessary.
1016 if (!blockInfo
.NoEscape
&& !blockInfo
.NeedsCopyDispose
)
1019 // Ignore __block captures; there's nothing special in the on-stack block
1020 // that we need to do for them.
1024 // Ignore objects that aren't destructed.
1025 QualType::DestructionKind dtorKind
= type
.isDestructedType();
1026 if (dtorKind
== QualType::DK_none
)
1029 CodeGenFunction::Destroyer
*destroyer
;
1031 // Block captures count as local values and have imprecise semantics.
1032 // They also can't be arrays, so need to worry about that.
1034 // For const-qualified captures, emit clang.arc.use to ensure the captured
1035 // object doesn't get released while we are still depending on its validity
1036 // within the block.
1037 if (type
.isConstQualified() &&
1038 type
.getObjCLifetime() == Qualifiers::OCL_Strong
&&
1039 CGM
.getCodeGenOpts().OptimizationLevel
!= 0) {
1040 assert(CGM
.getLangOpts().ObjCAutoRefCount
&&
1041 "expected ObjC ARC to be enabled");
1042 destroyer
= emitARCIntrinsicUse
;
1043 } else if (dtorKind
== QualType::DK_objc_strong_lifetime
) {
1044 destroyer
= destroyARCStrongImprecise
;
1046 destroyer
= getDestroyer(dtorKind
);
1049 CleanupKind cleanupKind
= NormalCleanup
;
1050 bool useArrayEHCleanup
= needsEHCleanup(dtorKind
);
1051 if (useArrayEHCleanup
)
1052 cleanupKind
= NormalAndEHCleanup
;
1054 // Extend the lifetime of the capture to the end of the scope enclosing the
1055 // block expression except when the block decl is in the list of RetExpr's
1056 // cleanup objects, in which case its lifetime ends after the full
1058 auto IsBlockDeclInRetExpr
= [&]() {
1059 auto *EWC
= llvm::dyn_cast_or_null
<ExprWithCleanups
>(RetExpr
);
1061 for (auto &C
: EWC
->getObjects())
1062 if (auto *BD
= C
.dyn_cast
<BlockDecl
*>())
1063 if (BD
== blockDecl
)
1068 if (IsBlockDeclInRetExpr())
1069 pushDestroy(cleanupKind
, blockField
, type
, destroyer
, useArrayEHCleanup
);
1071 pushLifetimeExtendedDestroy(cleanupKind
, blockField
, type
, destroyer
,
1075 // Cast to the converted block-pointer type, which happens (somewhat
1076 // unfortunately) to be a pointer to function type.
1077 llvm::Value
*result
= Builder
.CreatePointerCast(
1078 blockAddr
.getPointer(), ConvertType(blockInfo
.getBlockExpr()->getType()));
1081 CGM
.getOpenCLRuntime().recordBlockInfo(blockInfo
.BlockExpression
, InvokeFn
,
1082 result
, blockInfo
.StructureType
);
1089 llvm::Type
*CodeGenModule::getBlockDescriptorType() {
1090 if (BlockDescriptorType
)
1091 return BlockDescriptorType
;
1093 llvm::Type
*UnsignedLongTy
=
1094 getTypes().ConvertType(getContext().UnsignedLongTy
);
1096 // struct __block_descriptor {
1097 // unsigned long reserved;
1098 // unsigned long block_size;
1100 // // later, the following will be added
1103 // void (*copyHelper)();
1104 // void (*copyHelper)();
1105 // } helpers; // !!! optional
1107 // const char *signature; // the block signature
1108 // const char *layout; // reserved
1110 BlockDescriptorType
= llvm::StructType::create(
1111 "struct.__block_descriptor", UnsignedLongTy
, UnsignedLongTy
);
1113 // Now form a pointer to that.
1114 unsigned AddrSpace
= 0;
1115 if (getLangOpts().OpenCL
)
1116 AddrSpace
= getContext().getTargetAddressSpace(LangAS::opencl_constant
);
1117 BlockDescriptorType
= llvm::PointerType::get(BlockDescriptorType
, AddrSpace
);
1118 return BlockDescriptorType
;
1121 llvm::Type
*CodeGenModule::getGenericBlockLiteralType() {
1122 if (GenericBlockLiteralType
)
1123 return GenericBlockLiteralType
;
1125 llvm::Type
*BlockDescPtrTy
= getBlockDescriptorType();
1127 if (getLangOpts().OpenCL
) {
1128 // struct __opencl_block_literal_generic {
1131 // __generic void *__invoke;
1132 // /* custom fields */
1134 SmallVector
<llvm::Type
*, 8> StructFields(
1135 {IntTy
, IntTy
, getOpenCLRuntime().getGenericVoidPointerType()});
1136 if (auto *Helper
= getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1137 llvm::append_range(StructFields
, Helper
->getCustomFieldTypes());
1139 GenericBlockLiteralType
= llvm::StructType::create(
1140 StructFields
, "struct.__opencl_block_literal_generic");
1142 // struct __block_literal_generic {
1146 // void (*__invoke)(void *);
1147 // struct __block_descriptor *__descriptor;
1149 GenericBlockLiteralType
=
1150 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy
,
1151 IntTy
, IntTy
, VoidPtrTy
, BlockDescPtrTy
);
1154 return GenericBlockLiteralType
;
1157 RValue
CodeGenFunction::EmitBlockCallExpr(const CallExpr
*E
,
1158 ReturnValueSlot ReturnValue
) {
1159 const auto *BPT
= E
->getCallee()->getType()->castAs
<BlockPointerType
>();
1160 llvm::Value
*BlockPtr
= EmitScalarExpr(E
->getCallee());
1161 llvm::Type
*GenBlockTy
= CGM
.getGenericBlockLiteralType();
1162 llvm::Value
*Func
= nullptr;
1163 QualType FnType
= BPT
->getPointeeType();
1164 ASTContext
&Ctx
= getContext();
1167 if (getLangOpts().OpenCL
) {
1168 // For OpenCL, BlockPtr is already casted to generic block literal.
1170 // First argument of a block call is a generic block literal casted to
1171 // generic void pointer, i.e. i8 addrspace(4)*
1172 llvm::Type
*GenericVoidPtrTy
=
1173 CGM
.getOpenCLRuntime().getGenericVoidPointerType();
1174 llvm::Value
*BlockDescriptor
= Builder
.CreatePointerCast(
1175 BlockPtr
, GenericVoidPtrTy
);
1176 QualType VoidPtrQualTy
= Ctx
.getPointerType(
1177 Ctx
.getAddrSpaceQualType(Ctx
.VoidTy
, LangAS::opencl_generic
));
1178 Args
.add(RValue::get(BlockDescriptor
), VoidPtrQualTy
);
1179 // And the rest of the arguments.
1180 EmitCallArgs(Args
, FnType
->getAs
<FunctionProtoType
>(), E
->arguments());
1182 // We *can* call the block directly unless it is a function argument.
1183 if (!isa
<ParmVarDecl
>(E
->getCalleeDecl()))
1184 Func
= CGM
.getOpenCLRuntime().getInvokeFunction(E
->getCallee());
1186 llvm::Value
*FuncPtr
= Builder
.CreateStructGEP(GenBlockTy
, BlockPtr
, 2);
1187 Func
= Builder
.CreateAlignedLoad(GenericVoidPtrTy
, FuncPtr
,
1191 // Bitcast the block literal to a generic block literal.
1192 BlockPtr
= Builder
.CreatePointerCast(
1193 BlockPtr
, llvm::PointerType::get(GenBlockTy
, 0), "block.literal");
1194 // Get pointer to the block invoke function
1195 llvm::Value
*FuncPtr
= Builder
.CreateStructGEP(GenBlockTy
, BlockPtr
, 3);
1197 // First argument is a block literal casted to a void pointer
1198 BlockPtr
= Builder
.CreatePointerCast(BlockPtr
, VoidPtrTy
);
1199 Args
.add(RValue::get(BlockPtr
), Ctx
.VoidPtrTy
);
1200 // And the rest of the arguments.
1201 EmitCallArgs(Args
, FnType
->getAs
<FunctionProtoType
>(), E
->arguments());
1203 // Load the function.
1204 Func
= Builder
.CreateAlignedLoad(VoidPtrTy
, FuncPtr
, getPointerAlign());
1207 const FunctionType
*FuncTy
= FnType
->castAs
<FunctionType
>();
1208 const CGFunctionInfo
&FnInfo
=
1209 CGM
.getTypes().arrangeBlockFunctionCall(Args
, FuncTy
);
1211 // Cast the function pointer to the right type.
1212 llvm::Type
*BlockFTy
= CGM
.getTypes().GetFunctionType(FnInfo
);
1214 llvm::Type
*BlockFTyPtr
= llvm::PointerType::getUnqual(BlockFTy
);
1215 Func
= Builder
.CreatePointerCast(Func
, BlockFTyPtr
);
1217 // Prepare the callee.
1218 CGCallee
Callee(CGCalleeInfo(), Func
);
1220 // And call the block.
1221 return EmitCall(FnInfo
, Callee
, ReturnValue
, Args
);
1224 Address
CodeGenFunction::GetAddrOfBlockDecl(const VarDecl
*variable
) {
1225 assert(BlockInfo
&& "evaluating block ref without block information?");
1226 const CGBlockInfo::Capture
&capture
= BlockInfo
->getCapture(variable
);
1228 // Handle constant captures.
1229 if (capture
.isConstant()) return LocalDeclMap
.find(variable
)->second
;
1231 Address addr
= Builder
.CreateStructGEP(LoadBlockStruct(), capture
.getIndex(),
1232 "block.capture.addr");
1234 if (variable
->isEscapingByref()) {
1235 // addr should be a void** right now. Load, then cast the result
1238 auto &byrefInfo
= getBlockByrefInfo(variable
);
1239 addr
= Address(Builder
.CreateLoad(addr
), byrefInfo
.Type
,
1240 byrefInfo
.ByrefAlignment
);
1242 addr
= emitBlockByrefAddress(addr
, byrefInfo
, /*follow*/ true,
1243 variable
->getName());
1246 assert((!variable
->isNonEscapingByref() ||
1247 capture
.fieldType()->isReferenceType()) &&
1248 "the capture field of a non-escaping variable should have a "
1250 if (capture
.fieldType()->isReferenceType())
1251 addr
= EmitLoadOfReference(MakeAddrLValue(addr
, capture
.fieldType()));
1256 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr
*BE
,
1257 llvm::Constant
*Addr
) {
1258 bool Ok
= EmittedGlobalBlocks
.insert(std::make_pair(BE
, Addr
)).second
;
1260 assert(Ok
&& "Trying to replace an already-existing global block!");
1264 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr
*BE
,
1266 if (llvm::Constant
*Block
= getAddrOfGlobalBlockIfEmitted(BE
))
1269 CGBlockInfo
blockInfo(BE
->getBlockDecl(), Name
);
1270 blockInfo
.BlockExpression
= BE
;
1272 // Compute information about the layout, etc., of this block.
1273 computeBlockInfo(*this, nullptr, blockInfo
);
1275 // Using that metadata, generate the actual block function.
1277 CodeGenFunction::DeclMapTy LocalDeclMap
;
1278 CodeGenFunction(*this).GenerateBlockFunction(
1279 GlobalDecl(), blockInfo
, LocalDeclMap
,
1280 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1283 return getAddrOfGlobalBlockIfEmitted(BE
);
1286 static llvm::Constant
*buildGlobalBlock(CodeGenModule
&CGM
,
1287 const CGBlockInfo
&blockInfo
,
1288 llvm::Constant
*blockFn
) {
1289 assert(blockInfo
.CanBeGlobal
);
1290 // Callers should detect this case on their own: calling this function
1291 // generally requires computing layout information, which is a waste of time
1292 // if we've already emitted this block.
1293 assert(!CGM
.getAddrOfGlobalBlockIfEmitted(blockInfo
.BlockExpression
) &&
1294 "Refusing to re-emit a global block.");
1296 // Generate the constants for the block literal initializer.
1297 ConstantInitBuilder
builder(CGM
);
1298 auto fields
= builder
.beginStruct();
1300 bool IsOpenCL
= CGM
.getLangOpts().OpenCL
;
1301 bool IsWindows
= CGM
.getTarget().getTriple().isOSWindows();
1305 fields
.addNullPointer(CGM
.Int8PtrPtrTy
);
1307 fields
.add(CGM
.getNSConcreteGlobalBlock());
1310 BlockFlags flags
= BLOCK_IS_GLOBAL
| BLOCK_HAS_SIGNATURE
;
1311 if (blockInfo
.UsesStret
)
1312 flags
|= BLOCK_USE_STRET
;
1314 fields
.addInt(CGM
.IntTy
, flags
.getBitMask());
1317 fields
.addInt(CGM
.IntTy
, 0);
1319 fields
.addInt(CGM
.IntTy
, blockInfo
.BlockSize
.getQuantity());
1320 fields
.addInt(CGM
.IntTy
, blockInfo
.BlockAlign
.getQuantity());
1324 fields
.add(blockFn
);
1328 fields
.add(buildBlockDescriptor(CGM
, blockInfo
));
1329 } else if (auto *Helper
=
1330 CGM
.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1331 for (auto *I
: Helper
->getCustomFieldValues(CGM
, blockInfo
)) {
1336 unsigned AddrSpace
= 0;
1337 if (CGM
.getContext().getLangOpts().OpenCL
)
1338 AddrSpace
= CGM
.getContext().getTargetAddressSpace(LangAS::opencl_global
);
1340 llvm::GlobalVariable
*literal
= fields
.finishAndCreateGlobal(
1341 "__block_literal_global", blockInfo
.BlockAlign
,
1342 /*constant*/ !IsWindows
, llvm::GlobalVariable::InternalLinkage
, AddrSpace
);
1344 literal
->addAttribute("objc_arc_inert");
1346 // Windows does not allow globals to be initialised to point to globals in
1347 // different DLLs. Any such variables must run code to initialise them.
1349 auto *Init
= llvm::Function::Create(llvm::FunctionType::get(CGM
.VoidTy
,
1350 {}), llvm::GlobalValue::InternalLinkage
, ".block_isa_init",
1352 llvm::IRBuilder
<> b(llvm::BasicBlock::Create(CGM
.getLLVMContext(), "entry",
1354 b
.CreateAlignedStore(CGM
.getNSConcreteGlobalBlock(),
1355 b
.CreateStructGEP(literal
->getValueType(), literal
, 0),
1356 CGM
.getPointerAlign().getAsAlign());
1358 // We can't use the normal LLVM global initialisation array, because we
1359 // need to specify that this runs early in library initialisation.
1360 auto *InitVar
= new llvm::GlobalVariable(CGM
.getModule(), Init
->getType(),
1361 /*isConstant*/true, llvm::GlobalValue::InternalLinkage
,
1362 Init
, ".block_isa_init_ptr");
1363 InitVar
->setSection(".CRT$XCLa");
1364 CGM
.addUsedGlobal(InitVar
);
1367 // Return a constant of the appropriately-casted type.
1368 llvm::Type
*RequiredType
=
1369 CGM
.getTypes().ConvertType(blockInfo
.getBlockExpr()->getType());
1370 llvm::Constant
*Result
=
1371 llvm::ConstantExpr::getPointerCast(literal
, RequiredType
);
1372 CGM
.setAddrOfGlobalBlock(blockInfo
.BlockExpression
, Result
);
1373 if (CGM
.getContext().getLangOpts().OpenCL
)
1374 CGM
.getOpenCLRuntime().recordBlockInfo(
1375 blockInfo
.BlockExpression
,
1376 cast
<llvm::Function
>(blockFn
->stripPointerCasts()), Result
,
1377 literal
->getValueType());
1381 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl
*D
,
1384 assert(BlockInfo
&& "not emitting prologue of block invocation function?!");
1386 // Allocate a stack slot like for any local variable to guarantee optimal
1387 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1388 Address alloc
= CreateMemTemp(D
->getType(), D
->getName() + ".addr");
1389 Builder
.CreateStore(arg
, alloc
);
1390 if (CGDebugInfo
*DI
= getDebugInfo()) {
1391 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
1392 DI
->setLocation(D
->getLocation());
1393 DI
->EmitDeclareOfBlockLiteralArgVariable(
1394 *BlockInfo
, D
->getName(), argNum
,
1395 cast
<llvm::AllocaInst
>(alloc
.getPointer()), Builder
);
1399 SourceLocation StartLoc
= BlockInfo
->getBlockExpr()->getBody()->getBeginLoc();
1400 ApplyDebugLocation
Scope(*this, StartLoc
);
1402 // Instead of messing around with LocalDeclMap, just set the value
1403 // directly as BlockPointer.
1404 BlockPointer
= Builder
.CreatePointerCast(
1406 llvm::PointerType::get(
1408 getContext().getLangOpts().OpenCL
1409 ? getContext().getTargetAddressSpace(LangAS::opencl_generic
)
1414 Address
CodeGenFunction::LoadBlockStruct() {
1415 assert(BlockInfo
&& "not in a block invocation function!");
1416 assert(BlockPointer
&& "no block pointer set!");
1417 return Address(BlockPointer
, BlockInfo
->StructureType
, BlockInfo
->BlockAlign
);
1420 llvm::Function
*CodeGenFunction::GenerateBlockFunction(
1421 GlobalDecl GD
, const CGBlockInfo
&blockInfo
, const DeclMapTy
&ldm
,
1422 bool IsLambdaConversionToBlock
, bool BuildGlobalBlock
) {
1423 const BlockDecl
*blockDecl
= blockInfo
.getBlockDecl();
1427 CurEHLocation
= blockInfo
.getBlockExpr()->getEndLoc();
1429 BlockInfo
= &blockInfo
;
1431 // Arrange for local static and local extern declarations to appear
1432 // to be local to this function as well, in case they're directly
1433 // referenced in a block.
1434 for (DeclMapTy::const_iterator i
= ldm
.begin(), e
= ldm
.end(); i
!= e
; ++i
) {
1435 const auto *var
= dyn_cast
<VarDecl
>(i
->first
);
1436 if (var
&& !var
->hasLocalStorage())
1437 setAddrOfLocalVar(var
, i
->second
);
1440 // Begin building the function declaration.
1442 // Build the argument list.
1443 FunctionArgList args
;
1445 // The first argument is the block pointer. Just take it as a void*
1446 // and cast it later.
1447 QualType selfTy
= getContext().VoidPtrTy
;
1449 // For OpenCL passed block pointer can be private AS local variable or
1450 // global AS program scope variable (for the case with and without captures).
1451 // Generic AS is used therefore to be able to accommodate both private and
1452 // generic AS in one implementation.
1453 if (getLangOpts().OpenCL
)
1454 selfTy
= getContext().getPointerType(getContext().getAddrSpaceQualType(
1455 getContext().VoidTy
, LangAS::opencl_generic
));
1457 IdentifierInfo
*II
= &CGM
.getContext().Idents
.get(".block_descriptor");
1459 ImplicitParamDecl
SelfDecl(getContext(), const_cast<BlockDecl
*>(blockDecl
),
1460 SourceLocation(), II
, selfTy
,
1461 ImplicitParamDecl::ObjCSelf
);
1462 args
.push_back(&SelfDecl
);
1464 // Now add the rest of the parameters.
1465 args
.append(blockDecl
->param_begin(), blockDecl
->param_end());
1467 // Create the function declaration.
1468 const FunctionProtoType
*fnType
= blockInfo
.getBlockExpr()->getFunctionType();
1469 const CGFunctionInfo
&fnInfo
=
1470 CGM
.getTypes().arrangeBlockFunctionDeclaration(fnType
, args
);
1471 if (CGM
.ReturnSlotInterferesWithArgs(fnInfo
))
1472 blockInfo
.UsesStret
= true;
1474 llvm::FunctionType
*fnLLVMType
= CGM
.getTypes().GetFunctionType(fnInfo
);
1476 StringRef name
= CGM
.getBlockMangledName(GD
, blockDecl
);
1477 llvm::Function
*fn
= llvm::Function::Create(
1478 fnLLVMType
, llvm::GlobalValue::InternalLinkage
, name
, &CGM
.getModule());
1479 CGM
.SetInternalFunctionAttributes(blockDecl
, fn
, fnInfo
);
1481 if (BuildGlobalBlock
) {
1482 auto GenVoidPtrTy
= getContext().getLangOpts().OpenCL
1483 ? CGM
.getOpenCLRuntime().getGenericVoidPointerType()
1485 buildGlobalBlock(CGM
, blockInfo
,
1486 llvm::ConstantExpr::getPointerCast(fn
, GenVoidPtrTy
));
1489 // Begin generating the function.
1490 StartFunction(blockDecl
, fnType
->getReturnType(), fn
, fnInfo
, args
,
1491 blockDecl
->getLocation(),
1492 blockInfo
.getBlockExpr()->getBody()->getBeginLoc());
1494 // Okay. Undo some of what StartFunction did.
1496 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1497 // won't delete the dbg.declare intrinsics for captured variables.
1498 llvm::Value
*BlockPointerDbgLoc
= BlockPointer
;
1499 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
1500 // Allocate a stack slot for it, so we can point the debugger to it
1501 Address Alloca
= CreateTempAlloca(BlockPointer
->getType(),
1504 // Set the DebugLocation to empty, so the store is recognized as a
1505 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1506 auto NL
= ApplyDebugLocation::CreateEmpty(*this);
1507 Builder
.CreateStore(BlockPointer
, Alloca
);
1508 BlockPointerDbgLoc
= Alloca
.getPointer();
1511 // If we have a C++ 'this' reference, go ahead and force it into
1513 if (blockDecl
->capturesCXXThis()) {
1514 Address addr
= Builder
.CreateStructGEP(
1515 LoadBlockStruct(), blockInfo
.CXXThisIndex
, "block.captured-this");
1516 CXXThisValue
= Builder
.CreateLoad(addr
, "this");
1519 // Also force all the constant captures.
1520 for (const auto &CI
: blockDecl
->captures()) {
1521 const VarDecl
*variable
= CI
.getVariable();
1522 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
1523 if (!capture
.isConstant()) continue;
1525 CharUnits align
= getContext().getDeclAlign(variable
);
1527 CreateMemTemp(variable
->getType(), align
, "block.captured-const");
1529 Builder
.CreateStore(capture
.getConstant(), alloca
);
1531 setAddrOfLocalVar(variable
, alloca
);
1534 // Save a spot to insert the debug information for all the DeclRefExprs.
1535 llvm::BasicBlock
*entry
= Builder
.GetInsertBlock();
1536 llvm::BasicBlock::iterator entry_ptr
= Builder
.GetInsertPoint();
1539 if (IsLambdaConversionToBlock
)
1540 EmitLambdaBlockInvokeBody();
1542 PGO
.assignRegionCounters(GlobalDecl(blockDecl
), fn
);
1543 incrementProfileCounter(blockDecl
->getBody());
1544 EmitStmt(blockDecl
->getBody());
1547 // Remember where we were...
1548 llvm::BasicBlock
*resume
= Builder
.GetInsertBlock();
1550 // Go back to the entry.
1552 Builder
.SetInsertPoint(entry
, entry_ptr
);
1554 // Emit debug information for all the DeclRefExprs.
1555 // FIXME: also for 'this'
1556 if (CGDebugInfo
*DI
= getDebugInfo()) {
1557 for (const auto &CI
: blockDecl
->captures()) {
1558 const VarDecl
*variable
= CI
.getVariable();
1559 DI
->EmitLocation(Builder
, variable
->getLocation());
1561 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
1562 const CGBlockInfo::Capture
&capture
= blockInfo
.getCapture(variable
);
1563 if (capture
.isConstant()) {
1564 auto addr
= LocalDeclMap
.find(variable
)->second
;
1565 (void)DI
->EmitDeclareOfAutoVariable(variable
, addr
.getPointer(),
1570 DI
->EmitDeclareOfBlockDeclRefVariable(
1571 variable
, BlockPointerDbgLoc
, Builder
, blockInfo
,
1572 entry_ptr
== entry
->end() ? nullptr : &*entry_ptr
);
1575 // Recover location if it was changed in the above loop.
1576 DI
->EmitLocation(Builder
,
1577 cast
<CompoundStmt
>(blockDecl
->getBody())->getRBracLoc());
1580 // And resume where we left off.
1581 if (resume
== nullptr)
1582 Builder
.ClearInsertionPoint();
1584 Builder
.SetInsertPoint(resume
);
1586 FinishFunction(cast
<CompoundStmt
>(blockDecl
->getBody())->getRBracLoc());
1591 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
1592 computeCopyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
1593 const LangOptions
&LangOpts
) {
1594 if (CI
.getCopyExpr()) {
1595 assert(!CI
.isByRef());
1596 // don't bother computing flags
1597 return std::make_pair(BlockCaptureEntityKind::CXXRecord
, BlockFieldFlags());
1599 BlockFieldFlags Flags
;
1600 if (CI
.isEscapingByref()) {
1601 Flags
= BLOCK_FIELD_IS_BYREF
;
1602 if (T
.isObjCGCWeak())
1603 Flags
|= BLOCK_FIELD_IS_WEAK
;
1604 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
1607 Flags
= BLOCK_FIELD_IS_OBJECT
;
1608 bool isBlockPointer
= T
->isBlockPointerType();
1610 Flags
= BLOCK_FIELD_IS_BLOCK
;
1612 switch (T
.isNonTrivialToPrimitiveCopy()) {
1613 case QualType::PCK_Struct
:
1614 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct
,
1616 case QualType::PCK_ARCWeak
:
1617 // We need to register __weak direct captures with the runtime.
1618 return std::make_pair(BlockCaptureEntityKind::ARCWeak
, Flags
);
1619 case QualType::PCK_ARCStrong
:
1620 // We need to retain the copied value for __strong direct captures.
1621 // If it's a block pointer, we have to copy the block and assign that to
1622 // the destination pointer, so we might as well use _Block_object_assign.
1623 // Otherwise we can avoid that.
1624 return std::make_pair(!isBlockPointer
? BlockCaptureEntityKind::ARCStrong
1625 : BlockCaptureEntityKind::BlockObject
,
1627 case QualType::PCK_Trivial
:
1628 case QualType::PCK_VolatileTrivial
: {
1629 if (!T
->isObjCRetainableType())
1630 // For all other types, the memcpy is fine.
1631 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1633 // Honor the inert __unsafe_unretained qualifier, which doesn't actually
1634 // make it into the type system.
1635 if (T
->isObjCInertUnsafeUnretainedType())
1636 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1638 // Special rules for ARC captures:
1639 Qualifiers QS
= T
.getQualifiers();
1641 // Non-ARC captures of retainable pointers are strong and
1642 // therefore require a call to _Block_object_assign.
1643 if (!QS
.getObjCLifetime() && !LangOpts
.ObjCAutoRefCount
)
1644 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
1646 // Otherwise the memcpy is fine.
1647 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
1650 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1654 /// Release a __block variable.
1655 struct CallBlockRelease final
: EHScopeStack::Cleanup
{
1657 BlockFieldFlags FieldFlags
;
1658 bool LoadBlockVarAddr
, CanThrow
;
1660 CallBlockRelease(Address Addr
, BlockFieldFlags Flags
, bool LoadValue
,
1662 : Addr(Addr
), FieldFlags(Flags
), LoadBlockVarAddr(LoadValue
),
1665 void Emit(CodeGenFunction
&CGF
, Flags flags
) override
{
1666 llvm::Value
*BlockVarAddr
;
1667 if (LoadBlockVarAddr
) {
1668 BlockVarAddr
= CGF
.Builder
.CreateLoad(Addr
);
1670 BlockVarAddr
= Addr
.getPointer();
1673 CGF
.BuildBlockRelease(BlockVarAddr
, FieldFlags
, CanThrow
);
1676 } // end anonymous namespace
1678 /// Check if \p T is a C++ class that has a destructor that can throw.
1679 bool CodeGenFunction::cxxDestructorCanThrow(QualType T
) {
1680 if (const auto *RD
= T
->getAsCXXRecordDecl())
1681 if (const CXXDestructorDecl
*DD
= RD
->getDestructor())
1682 return DD
->getType()->castAs
<FunctionProtoType
>()->canThrow();
1686 // Return a string that has the information about a capture.
1687 static std::string
getBlockCaptureStr(const CGBlockInfo::Capture
&Cap
,
1688 CaptureStrKind StrKind
,
1689 CharUnits BlockAlignment
,
1690 CodeGenModule
&CGM
) {
1692 ASTContext
&Ctx
= CGM
.getContext();
1693 const BlockDecl::Capture
&CI
= *Cap
.Cap
;
1694 QualType CaptureTy
= CI
.getVariable()->getType();
1696 BlockCaptureEntityKind Kind
;
1697 BlockFieldFlags Flags
;
1699 // CaptureStrKind::Merged should be passed only when the operations and the
1700 // flags are the same for copy and dispose.
1701 assert((StrKind
!= CaptureStrKind::Merged
||
1702 (Cap
.CopyKind
== Cap
.DisposeKind
&&
1703 Cap
.CopyFlags
== Cap
.DisposeFlags
)) &&
1704 "different operations and flags");
1706 if (StrKind
== CaptureStrKind::DisposeHelper
) {
1707 Kind
= Cap
.DisposeKind
;
1708 Flags
= Cap
.DisposeFlags
;
1710 Kind
= Cap
.CopyKind
;
1711 Flags
= Cap
.CopyFlags
;
1715 case BlockCaptureEntityKind::CXXRecord
: {
1717 SmallString
<256> TyStr
;
1718 llvm::raw_svector_ostream
Out(TyStr
);
1719 CGM
.getCXXABI().getMangleContext().mangleTypeName(CaptureTy
, Out
);
1720 Str
+= llvm::to_string(TyStr
.size()) + TyStr
.c_str();
1723 case BlockCaptureEntityKind::ARCWeak
:
1726 case BlockCaptureEntityKind::ARCStrong
:
1729 case BlockCaptureEntityKind::BlockObject
: {
1730 const VarDecl
*Var
= CI
.getVariable();
1731 unsigned F
= Flags
.getBitMask();
1732 if (F
& BLOCK_FIELD_IS_BYREF
) {
1734 if (F
& BLOCK_FIELD_IS_WEAK
)
1737 // If CaptureStrKind::Merged is passed, check both the copy expression
1738 // and the destructor.
1739 if (StrKind
!= CaptureStrKind::DisposeHelper
) {
1740 if (Ctx
.getBlockVarCopyInit(Var
).canThrow())
1743 if (StrKind
!= CaptureStrKind::CopyHelper
) {
1744 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy
))
1749 assert((F
& BLOCK_FIELD_IS_OBJECT
) && "unexpected flag value");
1750 if (F
== BLOCK_FIELD_IS_BLOCK
)
1757 case BlockCaptureEntityKind::NonTrivialCStruct
: {
1758 bool IsVolatile
= CaptureTy
.isVolatileQualified();
1759 CharUnits Alignment
= BlockAlignment
.alignmentAtOffset(Cap
.getOffset());
1762 std::string FuncStr
;
1763 if (StrKind
== CaptureStrKind::DisposeHelper
)
1764 FuncStr
= CodeGenFunction::getNonTrivialDestructorStr(
1765 CaptureTy
, Alignment
, IsVolatile
, Ctx
);
1767 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1768 // It has all the information that the destructor string has.
1769 FuncStr
= CodeGenFunction::getNonTrivialCopyConstructorStr(
1770 CaptureTy
, Alignment
, IsVolatile
, Ctx
);
1771 // The underscore is necessary here because non-trivial copy constructor
1772 // and destructor strings can start with a number.
1773 Str
+= llvm::to_string(FuncStr
.size()) + "_" + FuncStr
;
1776 case BlockCaptureEntityKind::None
:
1783 static std::string
getCopyDestroyHelperFuncName(
1784 const SmallVectorImpl
<CGBlockInfo::Capture
> &Captures
,
1785 CharUnits BlockAlignment
, CaptureStrKind StrKind
, CodeGenModule
&CGM
) {
1786 assert((StrKind
== CaptureStrKind::CopyHelper
||
1787 StrKind
== CaptureStrKind::DisposeHelper
) &&
1788 "unexpected CaptureStrKind");
1789 std::string Name
= StrKind
== CaptureStrKind::CopyHelper
1790 ? "__copy_helper_block_"
1791 : "__destroy_helper_block_";
1792 if (CGM
.getLangOpts().Exceptions
)
1794 if (CGM
.getCodeGenOpts().ObjCAutoRefCountExceptions
)
1796 Name
+= llvm::to_string(BlockAlignment
.getQuantity()) + "_";
1798 for (auto &Cap
: Captures
) {
1799 if (Cap
.isConstantOrTrivial())
1801 Name
+= llvm::to_string(Cap
.getOffset().getQuantity());
1802 Name
+= getBlockCaptureStr(Cap
, StrKind
, BlockAlignment
, CGM
);
1808 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind
,
1809 Address Field
, QualType CaptureType
,
1810 BlockFieldFlags Flags
, bool ForCopyHelper
,
1811 VarDecl
*Var
, CodeGenFunction
&CGF
) {
1812 bool EHOnly
= ForCopyHelper
;
1814 switch (CaptureKind
) {
1815 case BlockCaptureEntityKind::CXXRecord
:
1816 case BlockCaptureEntityKind::ARCWeak
:
1817 case BlockCaptureEntityKind::NonTrivialCStruct
:
1818 case BlockCaptureEntityKind::ARCStrong
: {
1819 if (CaptureType
.isDestructedType() &&
1820 (!EHOnly
|| CGF
.needsEHCleanup(CaptureType
.isDestructedType()))) {
1821 CodeGenFunction::Destroyer
*Destroyer
=
1822 CaptureKind
== BlockCaptureEntityKind::ARCStrong
1823 ? CodeGenFunction::destroyARCStrongImprecise
1824 : CGF
.getDestroyer(CaptureType
.isDestructedType());
1827 : CGF
.getCleanupKind(CaptureType
.isDestructedType());
1828 CGF
.pushDestroy(Kind
, Field
, CaptureType
, Destroyer
, Kind
& EHCleanup
);
1832 case BlockCaptureEntityKind::BlockObject
: {
1833 if (!EHOnly
|| CGF
.getLangOpts().Exceptions
) {
1834 CleanupKind Kind
= EHOnly
? EHCleanup
: NormalAndEHCleanup
;
1835 // Calls to _Block_object_dispose along the EH path in the copy helper
1836 // function don't throw as newly-copied __block variables always have a
1837 // reference count of 2.
1839 !ForCopyHelper
&& CGF
.cxxDestructorCanThrow(CaptureType
);
1840 CGF
.enterByrefCleanup(Kind
, Field
, Flags
, /*LoadBlockVarAddr*/ true,
1845 case BlockCaptureEntityKind::None
:
1850 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType
,
1852 const CGFunctionInfo
&FI
,
1853 CodeGenModule
&CGM
) {
1854 if (CapturesNonExternalType
) {
1855 CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
1857 Fn
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1858 Fn
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
1859 CGM
.SetLLVMFunctionAttributes(GlobalDecl(), FI
, Fn
, /*IsThunk=*/false);
1860 CGM
.SetLLVMFunctionAttributesForDefinition(nullptr, Fn
);
1863 /// Generate the copy-helper function for a block closure object:
1864 /// static void block_copy_helper(block_t *dst, block_t *src);
1865 /// The runtime will have previously initialized 'dst' by doing a
1866 /// bit-copy of 'src'.
1868 /// Note that this copies an entire block closure object to the heap;
1869 /// it should not be confused with a 'byref copy helper', which moves
1870 /// the contents of an individual __block variable to the heap.
1872 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo
&blockInfo
) {
1873 std::string FuncName
= getCopyDestroyHelperFuncName(
1874 blockInfo
.SortedCaptures
, blockInfo
.BlockAlign
,
1875 CaptureStrKind::CopyHelper
, CGM
);
1877 if (llvm::GlobalValue
*Func
= CGM
.getModule().getNamedValue(FuncName
))
1878 return llvm::ConstantExpr::getBitCast(Func
, VoidPtrTy
);
1880 ASTContext
&C
= getContext();
1882 QualType ReturnTy
= C
.VoidTy
;
1884 FunctionArgList args
;
1885 ImplicitParamDecl
DstDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
1886 args
.push_back(&DstDecl
);
1887 ImplicitParamDecl
SrcDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
1888 args
.push_back(&SrcDecl
);
1890 const CGFunctionInfo
&FI
=
1891 CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
1893 // FIXME: it would be nice if these were mergeable with things with
1894 // identical semantics.
1895 llvm::FunctionType
*LTy
= CGM
.getTypes().GetFunctionType(FI
);
1897 llvm::Function
*Fn
=
1898 llvm::Function::Create(LTy
, llvm::GlobalValue::LinkOnceODRLinkage
,
1899 FuncName
, &CGM
.getModule());
1900 if (CGM
.supportsCOMDAT())
1901 Fn
->setComdat(CGM
.getModule().getOrInsertComdat(FuncName
));
1903 SmallVector
<QualType
, 2> ArgTys
;
1904 ArgTys
.push_back(C
.VoidPtrTy
);
1905 ArgTys
.push_back(C
.VoidPtrTy
);
1907 setBlockHelperAttributesVisibility(blockInfo
.CapturesNonExternalType
, Fn
, FI
,
1909 StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
1910 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
1912 Address src
= GetAddrOfLocalVar(&SrcDecl
);
1913 src
= Address(Builder
.CreateLoad(src
), blockInfo
.StructureType
,
1914 blockInfo
.BlockAlign
);
1916 Address dst
= GetAddrOfLocalVar(&DstDecl
);
1917 dst
= Address(Builder
.CreateLoad(dst
), blockInfo
.StructureType
,
1918 blockInfo
.BlockAlign
);
1920 for (auto &capture
: blockInfo
.SortedCaptures
) {
1921 if (capture
.isConstantOrTrivial())
1924 const BlockDecl::Capture
&CI
= *capture
.Cap
;
1925 QualType captureType
= CI
.getVariable()->getType();
1926 BlockFieldFlags flags
= capture
.CopyFlags
;
1928 unsigned index
= capture
.getIndex();
1929 Address srcField
= Builder
.CreateStructGEP(src
, index
);
1930 Address dstField
= Builder
.CreateStructGEP(dst
, index
);
1932 switch (capture
.CopyKind
) {
1933 case BlockCaptureEntityKind::CXXRecord
:
1934 // If there's an explicit copy expression, we do that.
1935 assert(CI
.getCopyExpr() && "copy expression for variable is missing");
1936 EmitSynthesizedCXXCopyCtor(dstField
, srcField
, CI
.getCopyExpr());
1938 case BlockCaptureEntityKind::ARCWeak
:
1939 EmitARCCopyWeak(dstField
, srcField
);
1941 case BlockCaptureEntityKind::NonTrivialCStruct
: {
1942 // If this is a C struct that requires non-trivial copy construction,
1943 // emit a call to its copy constructor.
1944 QualType varType
= CI
.getVariable()->getType();
1945 callCStructCopyConstructor(MakeAddrLValue(dstField
, varType
),
1946 MakeAddrLValue(srcField
, varType
));
1949 case BlockCaptureEntityKind::ARCStrong
: {
1950 llvm::Value
*srcValue
= Builder
.CreateLoad(srcField
, "blockcopy.src");
1951 // At -O0, store null into the destination field (so that the
1952 // storeStrong doesn't over-release) and then call storeStrong.
1953 // This is a workaround to not having an initStrong call.
1954 if (CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
1955 auto *ty
= cast
<llvm::PointerType
>(srcValue
->getType());
1956 llvm::Value
*null
= llvm::ConstantPointerNull::get(ty
);
1957 Builder
.CreateStore(null
, dstField
);
1958 EmitARCStoreStrongCall(dstField
, srcValue
, true);
1960 // With optimization enabled, take advantage of the fact that
1961 // the blocks runtime guarantees a memcpy of the block data, and
1962 // just emit a retain of the src field.
1964 EmitARCRetainNonBlock(srcValue
);
1966 // Unless EH cleanup is required, we don't need this anymore, so kill
1967 // it. It's not quite worth the annoyance to avoid creating it in the
1969 if (!needsEHCleanup(captureType
.isDestructedType()))
1970 cast
<llvm::Instruction
>(dstField
.getPointer())->eraseFromParent();
1974 case BlockCaptureEntityKind::BlockObject
: {
1975 llvm::Value
*srcValue
= Builder
.CreateLoad(srcField
, "blockcopy.src");
1976 llvm::Value
*dstAddr
= dstField
.getPointer();
1977 llvm::Value
*args
[] = {
1978 dstAddr
, srcValue
, llvm::ConstantInt::get(Int32Ty
, flags
.getBitMask())
1981 if (CI
.isByRef() && C
.getBlockVarCopyInit(CI
.getVariable()).canThrow())
1982 EmitRuntimeCallOrInvoke(CGM
.getBlockObjectAssign(), args
);
1984 EmitNounwindRuntimeCall(CGM
.getBlockObjectAssign(), args
);
1987 case BlockCaptureEntityKind::None
:
1991 // Ensure that we destroy the copied object if an exception is thrown later
1992 // in the helper function.
1993 pushCaptureCleanup(capture
.CopyKind
, dstField
, captureType
, flags
,
1994 /*ForCopyHelper*/ true, CI
.getVariable(), *this);
1999 return llvm::ConstantExpr::getBitCast(Fn
, VoidPtrTy
);
2002 static BlockFieldFlags
2003 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture
&CI
,
2005 BlockFieldFlags Flags
= BLOCK_FIELD_IS_OBJECT
;
2006 if (T
->isBlockPointerType())
2007 Flags
= BLOCK_FIELD_IS_BLOCK
;
2011 static std::pair
<BlockCaptureEntityKind
, BlockFieldFlags
>
2012 computeDestroyInfoForBlockCapture(const BlockDecl::Capture
&CI
, QualType T
,
2013 const LangOptions
&LangOpts
) {
2014 if (CI
.isEscapingByref()) {
2015 BlockFieldFlags Flags
= BLOCK_FIELD_IS_BYREF
;
2016 if (T
.isObjCGCWeak())
2017 Flags
|= BLOCK_FIELD_IS_WEAK
;
2018 return std::make_pair(BlockCaptureEntityKind::BlockObject
, Flags
);
2021 switch (T
.isDestructedType()) {
2022 case QualType::DK_cxx_destructor
:
2023 return std::make_pair(BlockCaptureEntityKind::CXXRecord
, BlockFieldFlags());
2024 case QualType::DK_objc_strong_lifetime
:
2025 // Use objc_storeStrong for __strong direct captures; the
2026 // dynamic tools really like it when we do this.
2027 return std::make_pair(BlockCaptureEntityKind::ARCStrong
,
2028 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2029 case QualType::DK_objc_weak_lifetime
:
2030 // Support __weak direct captures.
2031 return std::make_pair(BlockCaptureEntityKind::ARCWeak
,
2032 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2033 case QualType::DK_nontrivial_c_struct
:
2034 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct
,
2036 case QualType::DK_none
: {
2037 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2038 // But honor the inert __unsafe_unretained qualifier, which doesn't actually
2039 // make it into the type system.
2040 if (T
->isObjCRetainableType() && !T
.getQualifiers().hasObjCLifetime() &&
2041 !LangOpts
.ObjCAutoRefCount
&& !T
->isObjCInertUnsafeUnretainedType())
2042 return std::make_pair(BlockCaptureEntityKind::BlockObject
,
2043 getBlockFieldFlagsForObjCObjectPointer(CI
, T
));
2044 // Otherwise, we have nothing to do.
2045 return std::make_pair(BlockCaptureEntityKind::None
, BlockFieldFlags());
2048 llvm_unreachable("after exhaustive DestructionKind switch");
2051 /// Generate the destroy-helper function for a block closure object:
2052 /// static void block_destroy_helper(block_t *theBlock);
2054 /// Note that this destroys a heap-allocated block closure object;
2055 /// it should not be confused with a 'byref destroy helper', which
2056 /// destroys the heap-allocated contents of an individual __block
2059 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo
&blockInfo
) {
2060 std::string FuncName
= getCopyDestroyHelperFuncName(
2061 blockInfo
.SortedCaptures
, blockInfo
.BlockAlign
,
2062 CaptureStrKind::DisposeHelper
, CGM
);
2064 if (llvm::GlobalValue
*Func
= CGM
.getModule().getNamedValue(FuncName
))
2065 return llvm::ConstantExpr::getBitCast(Func
, VoidPtrTy
);
2067 ASTContext
&C
= getContext();
2069 QualType ReturnTy
= C
.VoidTy
;
2071 FunctionArgList args
;
2072 ImplicitParamDecl
SrcDecl(C
, C
.VoidPtrTy
, ImplicitParamDecl::Other
);
2073 args
.push_back(&SrcDecl
);
2075 const CGFunctionInfo
&FI
=
2076 CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
2078 // FIXME: We'd like to put these into a mergable by content, with
2079 // internal linkage.
2080 llvm::FunctionType
*LTy
= CGM
.getTypes().GetFunctionType(FI
);
2082 llvm::Function
*Fn
=
2083 llvm::Function::Create(LTy
, llvm::GlobalValue::LinkOnceODRLinkage
,
2084 FuncName
, &CGM
.getModule());
2085 if (CGM
.supportsCOMDAT())
2086 Fn
->setComdat(CGM
.getModule().getOrInsertComdat(FuncName
));
2088 SmallVector
<QualType
, 1> ArgTys
;
2089 ArgTys
.push_back(C
.VoidPtrTy
);
2091 setBlockHelperAttributesVisibility(blockInfo
.CapturesNonExternalType
, Fn
, FI
,
2093 StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
2094 markAsIgnoreThreadCheckingAtRuntime(Fn
);
2096 auto AL
= ApplyDebugLocation::CreateArtificial(*this);
2098 Address src
= GetAddrOfLocalVar(&SrcDecl
);
2099 src
= Address(Builder
.CreateLoad(src
), blockInfo
.StructureType
,
2100 blockInfo
.BlockAlign
);
2102 CodeGenFunction::RunCleanupsScope
cleanups(*this);
2104 for (auto &capture
: blockInfo
.SortedCaptures
) {
2105 if (capture
.isConstantOrTrivial())
2108 const BlockDecl::Capture
&CI
= *capture
.Cap
;
2109 BlockFieldFlags flags
= capture
.DisposeFlags
;
2111 Address srcField
= Builder
.CreateStructGEP(src
, capture
.getIndex());
2113 pushCaptureCleanup(capture
.DisposeKind
, srcField
,
2114 CI
.getVariable()->getType(), flags
,
2115 /*ForCopyHelper*/ false, CI
.getVariable(), *this);
2118 cleanups
.ForceCleanup();
2122 return llvm::ConstantExpr::getBitCast(Fn
, VoidPtrTy
);
2127 /// Emits the copy/dispose helper functions for a __block object of id type.
2128 class ObjectByrefHelpers final
: public BlockByrefHelpers
{
2129 BlockFieldFlags Flags
;
2132 ObjectByrefHelpers(CharUnits alignment
, BlockFieldFlags flags
)
2133 : BlockByrefHelpers(alignment
), Flags(flags
) {}
2135 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2136 Address srcField
) override
{
2137 destField
= destField
.withElementType(CGF
.Int8Ty
);
2139 srcField
= srcField
.withElementType(CGF
.Int8PtrTy
);
2140 llvm::Value
*srcValue
= CGF
.Builder
.CreateLoad(srcField
);
2142 unsigned flags
= (Flags
| BLOCK_BYREF_CALLER
).getBitMask();
2144 llvm::Value
*flagsVal
= llvm::ConstantInt::get(CGF
.Int32Ty
, flags
);
2145 llvm::FunctionCallee fn
= CGF
.CGM
.getBlockObjectAssign();
2147 llvm::Value
*args
[] = { destField
.getPointer(), srcValue
, flagsVal
};
2148 CGF
.EmitNounwindRuntimeCall(fn
, args
);
2151 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2152 field
= field
.withElementType(CGF
.Int8PtrTy
);
2153 llvm::Value
*value
= CGF
.Builder
.CreateLoad(field
);
2155 CGF
.BuildBlockRelease(value
, Flags
| BLOCK_BYREF_CALLER
, false);
2158 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2159 id
.AddInteger(Flags
.getBitMask());
2163 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2164 class ARCWeakByrefHelpers final
: public BlockByrefHelpers
{
2166 ARCWeakByrefHelpers(CharUnits alignment
) : BlockByrefHelpers(alignment
) {}
2168 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2169 Address srcField
) override
{
2170 CGF
.EmitARCMoveWeak(destField
, srcField
);
2173 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2174 CGF
.EmitARCDestroyWeak(field
);
2177 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2178 // 0 is distinguishable from all pointers and byref flags
2183 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2184 /// that's not of block-pointer type.
2185 class ARCStrongByrefHelpers final
: public BlockByrefHelpers
{
2187 ARCStrongByrefHelpers(CharUnits alignment
) : BlockByrefHelpers(alignment
) {}
2189 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2190 Address srcField
) override
{
2191 // Do a "move" by copying the value and then zeroing out the old
2194 llvm::Value
*value
= CGF
.Builder
.CreateLoad(srcField
);
2197 llvm::ConstantPointerNull::get(cast
<llvm::PointerType
>(value
->getType()));
2199 if (CGF
.CGM
.getCodeGenOpts().OptimizationLevel
== 0) {
2200 CGF
.Builder
.CreateStore(null
, destField
);
2201 CGF
.EmitARCStoreStrongCall(destField
, value
, /*ignored*/ true);
2202 CGF
.EmitARCStoreStrongCall(srcField
, null
, /*ignored*/ true);
2205 CGF
.Builder
.CreateStore(value
, destField
);
2206 CGF
.Builder
.CreateStore(null
, srcField
);
2209 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2210 CGF
.EmitARCDestroyStrong(field
, ARCImpreciseLifetime
);
2213 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2214 // 1 is distinguishable from all pointers and byref flags
2219 /// Emits the copy/dispose helpers for an ARC __block __strong
2220 /// variable that's of block-pointer type.
2221 class ARCStrongBlockByrefHelpers final
: public BlockByrefHelpers
{
2223 ARCStrongBlockByrefHelpers(CharUnits alignment
)
2224 : BlockByrefHelpers(alignment
) {}
2226 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2227 Address srcField
) override
{
2228 // Do the copy with objc_retainBlock; that's all that
2229 // _Block_object_assign would do anyway, and we'd have to pass the
2230 // right arguments to make sure it doesn't get no-op'ed.
2231 llvm::Value
*oldValue
= CGF
.Builder
.CreateLoad(srcField
);
2232 llvm::Value
*copy
= CGF
.EmitARCRetainBlock(oldValue
, /*mandatory*/ true);
2233 CGF
.Builder
.CreateStore(copy
, destField
);
2236 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2237 CGF
.EmitARCDestroyStrong(field
, ARCImpreciseLifetime
);
2240 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2241 // 2 is distinguishable from all pointers and byref flags
2246 /// Emits the copy/dispose helpers for a __block variable with a
2247 /// nontrivial copy constructor or destructor.
2248 class CXXByrefHelpers final
: public BlockByrefHelpers
{
2250 const Expr
*CopyExpr
;
2253 CXXByrefHelpers(CharUnits alignment
, QualType type
,
2254 const Expr
*copyExpr
)
2255 : BlockByrefHelpers(alignment
), VarType(type
), CopyExpr(copyExpr
) {}
2257 bool needsCopy() const override
{ return CopyExpr
!= nullptr; }
2258 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2259 Address srcField
) override
{
2260 if (!CopyExpr
) return;
2261 CGF
.EmitSynthesizedCXXCopyCtor(destField
, srcField
, CopyExpr
);
2264 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2265 EHScopeStack::stable_iterator cleanupDepth
= CGF
.EHStack
.stable_begin();
2266 CGF
.PushDestructorCleanup(VarType
, field
);
2267 CGF
.PopCleanupBlocks(cleanupDepth
);
2270 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2271 id
.AddPointer(VarType
.getCanonicalType().getAsOpaquePtr());
2275 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2277 class NonTrivialCStructByrefHelpers final
: public BlockByrefHelpers
{
2281 NonTrivialCStructByrefHelpers(CharUnits alignment
, QualType type
)
2282 : BlockByrefHelpers(alignment
), VarType(type
) {}
2284 void emitCopy(CodeGenFunction
&CGF
, Address destField
,
2285 Address srcField
) override
{
2286 CGF
.callCStructMoveConstructor(CGF
.MakeAddrLValue(destField
, VarType
),
2287 CGF
.MakeAddrLValue(srcField
, VarType
));
2290 bool needsDispose() const override
{
2291 return VarType
.isDestructedType();
2294 void emitDispose(CodeGenFunction
&CGF
, Address field
) override
{
2295 EHScopeStack::stable_iterator cleanupDepth
= CGF
.EHStack
.stable_begin();
2296 CGF
.pushDestroy(VarType
.isDestructedType(), field
, VarType
);
2297 CGF
.PopCleanupBlocks(cleanupDepth
);
2300 void profileImpl(llvm::FoldingSetNodeID
&id
) const override
{
2301 id
.AddPointer(VarType
.getCanonicalType().getAsOpaquePtr());
2304 } // end anonymous namespace
2306 static llvm::Constant
*
2307 generateByrefCopyHelper(CodeGenFunction
&CGF
, const BlockByrefInfo
&byrefInfo
,
2308 BlockByrefHelpers
&generator
) {
2309 ASTContext
&Context
= CGF
.getContext();
2311 QualType ReturnTy
= Context
.VoidTy
;
2313 FunctionArgList args
;
2314 ImplicitParamDecl
Dst(Context
, Context
.VoidPtrTy
, ImplicitParamDecl::Other
);
2315 args
.push_back(&Dst
);
2317 ImplicitParamDecl
Src(Context
, Context
.VoidPtrTy
, ImplicitParamDecl::Other
);
2318 args
.push_back(&Src
);
2320 const CGFunctionInfo
&FI
=
2321 CGF
.CGM
.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy
, args
);
2323 llvm::FunctionType
*LTy
= CGF
.CGM
.getTypes().GetFunctionType(FI
);
2325 // FIXME: We'd like to put these into a mergable by content, with
2326 // internal linkage.
2327 llvm::Function
*Fn
=
2328 llvm::Function::Create(LTy
, llvm::GlobalValue::InternalLinkage
,
2329 "__Block_byref_object_copy_", &CGF
.CGM
.getModule());
2331 SmallVector
<QualType
, 2> ArgTys
;
2332 ArgTys
.push_back(Context
.VoidPtrTy
);
2333 ArgTys
.push_back(Context
.VoidPtrTy
);
2335 CGF
.CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
2337 CGF
.StartFunction(GlobalDecl(), ReturnTy
, Fn
, FI
, args
);
2338 // Create a scope with an artificial location for the body of this function.
2339 auto AL
= ApplyDebugLocation::CreateArtificial(CGF
);
2341 if (generator
.needsCopy()) {
2343 Address destField
= CGF
.GetAddrOfLocalVar(&Dst
);
2344 destField
= Address(CGF
.Builder
.CreateLoad(destField
), byrefInfo
.Type
,
2345 byrefInfo
.ByrefAlignment
);
2347 CGF
.emitBlockByrefAddress(destField
, byrefInfo
, false, "dest-object");
2350 Address srcField
= CGF
.GetAddrOfLocalVar(&Src
);
2351 srcField
= Address(CGF
.Builder
.CreateLoad(srcField
), byrefInfo
.Type
,
2352 byrefInfo
.ByrefAlignment
);
2354 CGF
.emitBlockByrefAddress(srcField
, byrefInfo
, false, "src-object");
2356 generator
.emitCopy(CGF
, destField
, srcField
);
2359 CGF
.FinishFunction();
2361 return llvm::ConstantExpr::getBitCast(Fn
, CGF
.Int8PtrTy
);
2364 /// Build the copy helper for a __block variable.
2365 static llvm::Constant
*buildByrefCopyHelper(CodeGenModule
&CGM
,
2366 const BlockByrefInfo
&byrefInfo
,
2367 BlockByrefHelpers
&generator
) {
2368 CodeGenFunction
CGF(CGM
);
2369 return generateByrefCopyHelper(CGF
, byrefInfo
, generator
);
2372 /// Generate code for a __block variable's dispose helper.
2373 static llvm::Constant
*
2374 generateByrefDisposeHelper(CodeGenFunction
&CGF
,
2375 const BlockByrefInfo
&byrefInfo
,
2376 BlockByrefHelpers
&generator
) {
2377 ASTContext
&Context
= CGF
.getContext();
2378 QualType R
= Context
.VoidTy
;
2380 FunctionArgList args
;
2381 ImplicitParamDecl
Src(CGF
.getContext(), Context
.VoidPtrTy
,
2382 ImplicitParamDecl::Other
);
2383 args
.push_back(&Src
);
2385 const CGFunctionInfo
&FI
=
2386 CGF
.CGM
.getTypes().arrangeBuiltinFunctionDeclaration(R
, args
);
2388 llvm::FunctionType
*LTy
= CGF
.CGM
.getTypes().GetFunctionType(FI
);
2390 // FIXME: We'd like to put these into a mergable by content, with
2391 // internal linkage.
2392 llvm::Function
*Fn
=
2393 llvm::Function::Create(LTy
, llvm::GlobalValue::InternalLinkage
,
2394 "__Block_byref_object_dispose_",
2395 &CGF
.CGM
.getModule());
2397 SmallVector
<QualType
, 1> ArgTys
;
2398 ArgTys
.push_back(Context
.VoidPtrTy
);
2400 CGF
.CGM
.SetInternalFunctionAttributes(GlobalDecl(), Fn
, FI
);
2402 CGF
.StartFunction(GlobalDecl(), R
, Fn
, FI
, args
);
2403 // Create a scope with an artificial location for the body of this function.
2404 auto AL
= ApplyDebugLocation::CreateArtificial(CGF
);
2406 if (generator
.needsDispose()) {
2407 Address addr
= CGF
.GetAddrOfLocalVar(&Src
);
2408 addr
= Address(CGF
.Builder
.CreateLoad(addr
), byrefInfo
.Type
,
2409 byrefInfo
.ByrefAlignment
);
2410 addr
= CGF
.emitBlockByrefAddress(addr
, byrefInfo
, false, "object");
2412 generator
.emitDispose(CGF
, addr
);
2415 CGF
.FinishFunction();
2417 return llvm::ConstantExpr::getBitCast(Fn
, CGF
.Int8PtrTy
);
2420 /// Build the dispose helper for a __block variable.
2421 static llvm::Constant
*buildByrefDisposeHelper(CodeGenModule
&CGM
,
2422 const BlockByrefInfo
&byrefInfo
,
2423 BlockByrefHelpers
&generator
) {
2424 CodeGenFunction
CGF(CGM
);
2425 return generateByrefDisposeHelper(CGF
, byrefInfo
, generator
);
2428 /// Lazily build the copy and dispose helpers for a __block variable
2429 /// with the given information.
2431 static T
*buildByrefHelpers(CodeGenModule
&CGM
, const BlockByrefInfo
&byrefInfo
,
2433 llvm::FoldingSetNodeID id
;
2434 generator
.Profile(id
);
2437 BlockByrefHelpers
*node
2438 = CGM
.ByrefHelpersCache
.FindNodeOrInsertPos(id
, insertPos
);
2439 if (node
) return static_cast<T
*>(node
);
2441 generator
.CopyHelper
= buildByrefCopyHelper(CGM
, byrefInfo
, generator
);
2442 generator
.DisposeHelper
= buildByrefDisposeHelper(CGM
, byrefInfo
, generator
);
2444 T
*copy
= new (CGM
.getContext()) T(std::forward
<T
>(generator
));
2445 CGM
.ByrefHelpersCache
.InsertNode(copy
, insertPos
);
2449 /// Build the copy and dispose helpers for the given __block variable
2450 /// emission. Places the helpers in the global cache. Returns null
2451 /// if no helpers are required.
2453 CodeGenFunction::buildByrefHelpers(llvm::StructType
&byrefType
,
2454 const AutoVarEmission
&emission
) {
2455 const VarDecl
&var
= *emission
.Variable
;
2456 assert(var
.isEscapingByref() &&
2457 "only escaping __block variables need byref helpers");
2459 QualType type
= var
.getType();
2461 auto &byrefInfo
= getBlockByrefInfo(&var
);
2463 // The alignment we care about for the purposes of uniquing byref
2464 // helpers is the alignment of the actual byref value field.
2465 CharUnits valueAlignment
=
2466 byrefInfo
.ByrefAlignment
.alignmentAtOffset(byrefInfo
.FieldOffset
);
2468 if (const CXXRecordDecl
*record
= type
->getAsCXXRecordDecl()) {
2469 const Expr
*copyExpr
=
2470 CGM
.getContext().getBlockVarCopyInit(&var
).getCopyExpr();
2471 if (!copyExpr
&& record
->hasTrivialDestructor()) return nullptr;
2473 return ::buildByrefHelpers(
2474 CGM
, byrefInfo
, CXXByrefHelpers(valueAlignment
, type
, copyExpr
));
2477 // If type is a non-trivial C struct type that is non-trivial to
2478 // destructly move or destroy, build the copy and dispose helpers.
2479 if (type
.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct
||
2480 type
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
2481 return ::buildByrefHelpers(
2482 CGM
, byrefInfo
, NonTrivialCStructByrefHelpers(valueAlignment
, type
));
2484 // Otherwise, if we don't have a retainable type, there's nothing to do.
2485 // that the runtime does extra copies.
2486 if (!type
->isObjCRetainableType()) return nullptr;
2488 Qualifiers qs
= type
.getQualifiers();
2490 // If we have lifetime, that dominates.
2491 if (Qualifiers::ObjCLifetime lifetime
= qs
.getObjCLifetime()) {
2493 case Qualifiers::OCL_None
: llvm_unreachable("impossible");
2495 // These are just bits as far as the runtime is concerned.
2496 case Qualifiers::OCL_ExplicitNone
:
2497 case Qualifiers::OCL_Autoreleasing
:
2500 // Tell the runtime that this is ARC __weak, called by the
2502 case Qualifiers::OCL_Weak
:
2503 return ::buildByrefHelpers(CGM
, byrefInfo
,
2504 ARCWeakByrefHelpers(valueAlignment
));
2506 // ARC __strong __block variables need to be retained.
2507 case Qualifiers::OCL_Strong
:
2508 // Block pointers need to be copied, and there's no direct
2509 // transfer possible.
2510 if (type
->isBlockPointerType()) {
2511 return ::buildByrefHelpers(CGM
, byrefInfo
,
2512 ARCStrongBlockByrefHelpers(valueAlignment
));
2514 // Otherwise, we transfer ownership of the retain from the stack
2517 return ::buildByrefHelpers(CGM
, byrefInfo
,
2518 ARCStrongByrefHelpers(valueAlignment
));
2521 llvm_unreachable("fell out of lifetime switch!");
2524 BlockFieldFlags flags
;
2525 if (type
->isBlockPointerType()) {
2526 flags
|= BLOCK_FIELD_IS_BLOCK
;
2527 } else if (CGM
.getContext().isObjCNSObjectType(type
) ||
2528 type
->isObjCObjectPointerType()) {
2529 flags
|= BLOCK_FIELD_IS_OBJECT
;
2534 if (type
.isObjCGCWeak())
2535 flags
|= BLOCK_FIELD_IS_WEAK
;
2537 return ::buildByrefHelpers(CGM
, byrefInfo
,
2538 ObjectByrefHelpers(valueAlignment
, flags
));
2541 Address
CodeGenFunction::emitBlockByrefAddress(Address baseAddr
,
2543 bool followForward
) {
2544 auto &info
= getBlockByrefInfo(var
);
2545 return emitBlockByrefAddress(baseAddr
, info
, followForward
, var
->getName());
2548 Address
CodeGenFunction::emitBlockByrefAddress(Address baseAddr
,
2549 const BlockByrefInfo
&info
,
2551 const llvm::Twine
&name
) {
2552 // Chase the forwarding address if requested.
2553 if (followForward
) {
2554 Address forwardingAddr
= Builder
.CreateStructGEP(baseAddr
, 1, "forwarding");
2555 baseAddr
= Address(Builder
.CreateLoad(forwardingAddr
), info
.Type
,
2556 info
.ByrefAlignment
);
2559 return Builder
.CreateStructGEP(baseAddr
, info
.FieldIndex
, name
);
2562 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2567 /// void *__forwarding;
2568 /// int32_t __flags;
2570 /// void *__copy_helper; // only if needed
2571 /// void *__destroy_helper; // only if needed
2572 /// void *__byref_variable_layout;// only if needed
2573 /// char padding[X]; // only if needed
2577 const BlockByrefInfo
&CodeGenFunction::getBlockByrefInfo(const VarDecl
*D
) {
2578 auto it
= BlockByrefInfos
.find(D
);
2579 if (it
!= BlockByrefInfos
.end())
2582 llvm::StructType
*byrefType
=
2583 llvm::StructType::create(getLLVMContext(),
2584 "struct.__block_byref_" + D
->getNameAsString());
2586 QualType Ty
= D
->getType();
2589 SmallVector
<llvm::Type
*, 8> types
;
2592 types
.push_back(Int8PtrTy
);
2593 size
+= getPointerSize();
2595 // void *__forwarding;
2596 types
.push_back(llvm::PointerType::getUnqual(byrefType
));
2597 size
+= getPointerSize();
2600 types
.push_back(Int32Ty
);
2601 size
+= CharUnits::fromQuantity(4);
2604 types
.push_back(Int32Ty
);
2605 size
+= CharUnits::fromQuantity(4);
2607 // Note that this must match *exactly* the logic in buildByrefHelpers.
2608 bool hasCopyAndDispose
= getContext().BlockRequiresCopying(Ty
, D
);
2609 if (hasCopyAndDispose
) {
2610 /// void *__copy_helper;
2611 types
.push_back(Int8PtrTy
);
2612 size
+= getPointerSize();
2614 /// void *__destroy_helper;
2615 types
.push_back(Int8PtrTy
);
2616 size
+= getPointerSize();
2619 bool HasByrefExtendedLayout
= false;
2620 Qualifiers::ObjCLifetime Lifetime
= Qualifiers::OCL_None
;
2621 if (getContext().getByrefLifetime(Ty
, Lifetime
, HasByrefExtendedLayout
) &&
2622 HasByrefExtendedLayout
) {
2623 /// void *__byref_variable_layout;
2624 types
.push_back(Int8PtrTy
);
2625 size
+= CharUnits::fromQuantity(PointerSizeInBytes
);
2629 llvm::Type
*varTy
= ConvertTypeForMem(Ty
);
2631 bool packed
= false;
2632 CharUnits varAlign
= getContext().getDeclAlign(D
);
2633 CharUnits varOffset
= size
.alignTo(varAlign
);
2635 // We may have to insert padding.
2636 if (varOffset
!= size
) {
2637 llvm::Type
*paddingTy
=
2638 llvm::ArrayType::get(Int8Ty
, (varOffset
- size
).getQuantity());
2640 types
.push_back(paddingTy
);
2643 // Conversely, we might have to prevent LLVM from inserting padding.
2644 } else if (CGM
.getDataLayout().getABITypeAlign(varTy
) >
2645 uint64_t(varAlign
.getQuantity())) {
2648 types
.push_back(varTy
);
2650 byrefType
->setBody(types
, packed
);
2652 BlockByrefInfo info
;
2653 info
.Type
= byrefType
;
2654 info
.FieldIndex
= types
.size() - 1;
2655 info
.FieldOffset
= varOffset
;
2656 info
.ByrefAlignment
= std::max(varAlign
, getPointerAlign());
2658 auto pair
= BlockByrefInfos
.insert({D
, info
});
2659 assert(pair
.second
&& "info was inserted recursively?");
2660 return pair
.first
->second
;
2663 /// Initialize the structural components of a __block variable, i.e.
2664 /// everything but the actual object.
2665 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission
&emission
) {
2666 // Find the address of the local.
2667 Address addr
= emission
.Addr
;
2669 // That's an alloca of the byref structure type.
2670 llvm::StructType
*byrefType
= cast
<llvm::StructType
>(addr
.getElementType());
2672 unsigned nextHeaderIndex
= 0;
2673 CharUnits nextHeaderOffset
;
2674 auto storeHeaderField
= [&](llvm::Value
*value
, CharUnits fieldSize
,
2675 const Twine
&name
) {
2676 auto fieldAddr
= Builder
.CreateStructGEP(addr
, nextHeaderIndex
, name
);
2677 Builder
.CreateStore(value
, fieldAddr
);
2680 nextHeaderOffset
+= fieldSize
;
2683 // Build the byref helpers if necessary. This is null if we don't need any.
2684 BlockByrefHelpers
*helpers
= buildByrefHelpers(*byrefType
, emission
);
2686 const VarDecl
&D
= *emission
.Variable
;
2687 QualType type
= D
.getType();
2689 bool HasByrefExtendedLayout
= false;
2690 Qualifiers::ObjCLifetime ByrefLifetime
= Qualifiers::OCL_None
;
2691 bool ByRefHasLifetime
=
2692 getContext().getByrefLifetime(type
, ByrefLifetime
, HasByrefExtendedLayout
);
2696 // Initialize the 'isa', which is just 0 or 1.
2698 if (type
.isObjCGCWeak())
2700 V
= Builder
.CreateIntToPtr(Builder
.getInt32(isa
), Int8PtrTy
, "isa");
2701 storeHeaderField(V
, getPointerSize(), "byref.isa");
2703 // Store the address of the variable into its own forwarding pointer.
2704 storeHeaderField(addr
.getPointer(), getPointerSize(), "byref.forwarding");
2707 // c) the flags field is set to either 0 if no helper functions are
2708 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2710 if (helpers
) flags
|= BLOCK_BYREF_HAS_COPY_DISPOSE
;
2711 if (ByRefHasLifetime
) {
2712 if (HasByrefExtendedLayout
) flags
|= BLOCK_BYREF_LAYOUT_EXTENDED
;
2713 else switch (ByrefLifetime
) {
2714 case Qualifiers::OCL_Strong
:
2715 flags
|= BLOCK_BYREF_LAYOUT_STRONG
;
2717 case Qualifiers::OCL_Weak
:
2718 flags
|= BLOCK_BYREF_LAYOUT_WEAK
;
2720 case Qualifiers::OCL_ExplicitNone
:
2721 flags
|= BLOCK_BYREF_LAYOUT_UNRETAINED
;
2723 case Qualifiers::OCL_None
:
2724 if (!type
->isObjCObjectPointerType() && !type
->isBlockPointerType())
2725 flags
|= BLOCK_BYREF_LAYOUT_NON_OBJECT
;
2730 if (CGM
.getLangOpts().ObjCGCBitmapPrint
) {
2731 printf("\n Inline flag for BYREF variable layout (%d):", flags
.getBitMask());
2732 if (flags
& BLOCK_BYREF_HAS_COPY_DISPOSE
)
2733 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2734 if (flags
& BLOCK_BYREF_LAYOUT_MASK
) {
2735 BlockFlags
ThisFlag(flags
.getBitMask() & BLOCK_BYREF_LAYOUT_MASK
);
2736 if (ThisFlag
== BLOCK_BYREF_LAYOUT_EXTENDED
)
2737 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2738 if (ThisFlag
== BLOCK_BYREF_LAYOUT_STRONG
)
2739 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2740 if (ThisFlag
== BLOCK_BYREF_LAYOUT_WEAK
)
2741 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2742 if (ThisFlag
== BLOCK_BYREF_LAYOUT_UNRETAINED
)
2743 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2744 if (ThisFlag
== BLOCK_BYREF_LAYOUT_NON_OBJECT
)
2745 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2750 storeHeaderField(llvm::ConstantInt::get(IntTy
, flags
.getBitMask()),
2751 getIntSize(), "byref.flags");
2753 CharUnits byrefSize
= CGM
.GetTargetTypeStoreSize(byrefType
);
2754 V
= llvm::ConstantInt::get(IntTy
, byrefSize
.getQuantity());
2755 storeHeaderField(V
, getIntSize(), "byref.size");
2758 storeHeaderField(helpers
->CopyHelper
, getPointerSize(),
2759 "byref.copyHelper");
2760 storeHeaderField(helpers
->DisposeHelper
, getPointerSize(),
2761 "byref.disposeHelper");
2764 if (ByRefHasLifetime
&& HasByrefExtendedLayout
) {
2765 auto layoutInfo
= CGM
.getObjCRuntime().BuildByrefLayout(CGM
, type
);
2766 storeHeaderField(layoutInfo
, getPointerSize(), "byref.layout");
2770 void CodeGenFunction::BuildBlockRelease(llvm::Value
*V
, BlockFieldFlags flags
,
2772 llvm::FunctionCallee F
= CGM
.getBlockObjectDispose();
2773 llvm::Value
*args
[] = {V
,
2774 llvm::ConstantInt::get(Int32Ty
, flags
.getBitMask())};
2777 EmitRuntimeCallOrInvoke(F
, args
);
2779 EmitNounwindRuntimeCall(F
, args
);
2782 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind
, Address Addr
,
2783 BlockFieldFlags Flags
,
2784 bool LoadBlockVarAddr
, bool CanThrow
) {
2785 EHStack
.pushCleanup
<CallBlockRelease
>(Kind
, Addr
, Flags
, LoadBlockVarAddr
,
2789 /// Adjust the declaration of something from the blocks API.
2790 static void configureBlocksRuntimeObject(CodeGenModule
&CGM
,
2791 llvm::Constant
*C
) {
2792 auto *GV
= cast
<llvm::GlobalValue
>(C
->stripPointerCasts());
2794 if (CGM
.getTarget().getTriple().isOSBinFormatCOFF()) {
2795 IdentifierInfo
&II
= CGM
.getContext().Idents
.get(C
->getName());
2796 TranslationUnitDecl
*TUDecl
= CGM
.getContext().getTranslationUnitDecl();
2797 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
2799 assert((isa
<llvm::Function
>(C
->stripPointerCasts()) ||
2800 isa
<llvm::GlobalVariable
>(C
->stripPointerCasts())) &&
2801 "expected Function or GlobalVariable");
2803 const NamedDecl
*ND
= nullptr;
2804 for (const auto *Result
: DC
->lookup(&II
))
2805 if ((ND
= dyn_cast
<FunctionDecl
>(Result
)) ||
2806 (ND
= dyn_cast
<VarDecl
>(Result
)))
2809 // TODO: support static blocks runtime
2810 if (GV
->isDeclaration() && (!ND
|| !ND
->hasAttr
<DLLExportAttr
>())) {
2811 GV
->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
2812 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
2814 GV
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
2815 GV
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
2819 if (CGM
.getLangOpts().BlocksRuntimeOptional
&& GV
->isDeclaration() &&
2820 GV
->hasExternalLinkage())
2821 GV
->setLinkage(llvm::GlobalValue::ExternalWeakLinkage
);
2823 CGM
.setDSOLocal(GV
);
2826 llvm::FunctionCallee
CodeGenModule::getBlockObjectDispose() {
2827 if (BlockObjectDispose
)
2828 return BlockObjectDispose
;
2830 llvm::Type
*args
[] = { Int8PtrTy
, Int32Ty
};
2831 llvm::FunctionType
*fty
2832 = llvm::FunctionType::get(VoidTy
, args
, false);
2833 BlockObjectDispose
= CreateRuntimeFunction(fty
, "_Block_object_dispose");
2834 configureBlocksRuntimeObject(
2835 *this, cast
<llvm::Constant
>(BlockObjectDispose
.getCallee()));
2836 return BlockObjectDispose
;
2839 llvm::FunctionCallee
CodeGenModule::getBlockObjectAssign() {
2840 if (BlockObjectAssign
)
2841 return BlockObjectAssign
;
2843 llvm::Type
*args
[] = { Int8PtrTy
, Int8PtrTy
, Int32Ty
};
2844 llvm::FunctionType
*fty
2845 = llvm::FunctionType::get(VoidTy
, args
, false);
2846 BlockObjectAssign
= CreateRuntimeFunction(fty
, "_Block_object_assign");
2847 configureBlocksRuntimeObject(
2848 *this, cast
<llvm::Constant
>(BlockObjectAssign
.getCallee()));
2849 return BlockObjectAssign
;
2852 llvm::Constant
*CodeGenModule::getNSConcreteGlobalBlock() {
2853 if (NSConcreteGlobalBlock
)
2854 return NSConcreteGlobalBlock
;
2856 NSConcreteGlobalBlock
= GetOrCreateLLVMGlobal(
2857 "_NSConcreteGlobalBlock", Int8PtrTy
, LangAS::Default
, nullptr);
2858 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock
);
2859 return NSConcreteGlobalBlock
;
2862 llvm::Constant
*CodeGenModule::getNSConcreteStackBlock() {
2863 if (NSConcreteStackBlock
)
2864 return NSConcreteStackBlock
;
2866 NSConcreteStackBlock
= GetOrCreateLLVMGlobal(
2867 "_NSConcreteStackBlock", Int8PtrTy
, LangAS::Default
, nullptr);
2868 configureBlocksRuntimeObject(*this, NSConcreteStackBlock
);
2869 return NSConcreteStackBlock
;