1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit blocks.
12 //===----------------------------------------------------------------------===//
16 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CGOpenCLRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/CodeGen/ConstantInitBuilder.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/ScopedPrinter.h"
33 using namespace clang;
34 using namespace CodeGen;
36 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
37 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
38 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
39 CapturesNonExternalType(false), LocalAddress(Address::invalid()),
40 StructureType(nullptr), Block(block), DominatingIP(nullptr) {
42 // Skip asm prefix, if any. 'name' is usually taken directly from
43 // the mangled name of the enclosing function.
44 if (!name.empty() && name[0] == '\01')
45 name = name.substr(1);
48 // Anchor the vtable to this translation unit.
49 BlockByrefHelpers::~BlockByrefHelpers() {}
51 /// Build the given block as a global block.
52 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo,
54 llvm::Constant *blockFn);
56 /// Build the helper function to copy a block.
57 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
62 /// Build the helper function to dispose of a block.
63 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
64 const CGBlockInfo &blockInfo) {
65 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
70 /// Represents a type of copy/destroy operation that should be performed for an
71 /// entity that's captured by a block.
72 enum class BlockCaptureEntityKind {
73 CXXRecord, // Copy or destroy
77 BlockObject, // Assign or release
81 /// Represents a captured entity that requires extra operations in order for
82 /// this entity to be copied or destroyed correctly.
83 struct BlockCaptureManagedEntity {
84 BlockCaptureEntityKind CopyKind, DisposeKind;
85 BlockFieldFlags CopyFlags, DisposeFlags;
86 const BlockDecl::Capture *CI;
87 const CGBlockInfo::Capture *Capture;
89 BlockCaptureManagedEntity(BlockCaptureEntityKind CopyType,
90 BlockCaptureEntityKind DisposeType,
91 BlockFieldFlags CopyFlags,
92 BlockFieldFlags DisposeFlags,
93 const BlockDecl::Capture &CI,
94 const CGBlockInfo::Capture &Capture)
95 : CopyKind(CopyType), DisposeKind(DisposeType), CopyFlags(CopyFlags),
96 DisposeFlags(DisposeFlags), CI(&CI), Capture(&Capture) {}
98 bool operator<(const BlockCaptureManagedEntity &Other) const {
99 return Capture->getOffset() < Other.Capture->getOffset();
103 enum class CaptureStrKind {
104 // String for the copy helper.
106 // String for the dispose helper.
108 // Merge the strings for the copy helper and dispose helper.
112 } // end anonymous namespace
114 static void findBlockCapturedManagedEntities(
115 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
116 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures);
118 static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
119 CaptureStrKind StrKind,
120 CharUnits BlockAlignment,
123 static std::string getBlockDescriptorName(const CGBlockInfo &BlockInfo,
124 CodeGenModule &CGM) {
125 std::string Name = "__block_descriptor_";
126 Name += llvm::to_string(BlockInfo.BlockSize.getQuantity()) + "_";
128 if (BlockInfo.needsCopyDisposeHelpers()) {
129 if (CGM.getLangOpts().Exceptions)
131 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
133 Name += llvm::to_string(BlockInfo.BlockAlign.getQuantity()) + "_";
135 SmallVector<BlockCaptureManagedEntity, 4> ManagedCaptures;
136 findBlockCapturedManagedEntities(BlockInfo, CGM.getContext().getLangOpts(),
139 for (const BlockCaptureManagedEntity &E : ManagedCaptures) {
140 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
142 if (E.CopyKind == E.DisposeKind) {
143 // If CopyKind and DisposeKind are the same, merge the capture
145 assert(E.CopyKind != BlockCaptureEntityKind::None &&
146 "shouldn't see BlockCaptureManagedEntity that is None");
147 Name += getBlockCaptureStr(E, CaptureStrKind::Merged,
148 BlockInfo.BlockAlign, CGM);
150 // If CopyKind and DisposeKind are not the same, which can happen when
151 // either Kind is None or the captured object is a __strong block,
152 // concatenate the copy and dispose strings.
153 Name += getBlockCaptureStr(E, CaptureStrKind::CopyHelper,
154 BlockInfo.BlockAlign, CGM);
155 Name += getBlockCaptureStr(E, CaptureStrKind::DisposeHelper,
156 BlockInfo.BlockAlign, CGM);
162 std::string TypeAtEncoding =
163 CGM.getContext().getObjCEncodingForBlock(BlockInfo.getBlockExpr());
164 /// Replace occurrences of '@' with '\1'. '@' is reserved on ELF platforms as
165 /// a separator between symbol name and symbol version.
166 std::replace(TypeAtEncoding.begin(), TypeAtEncoding.end(), '@', '\1');
167 Name += "e" + llvm::to_string(TypeAtEncoding.size()) + "_" + TypeAtEncoding;
168 Name += "l" + CGM.getObjCRuntime().getRCBlockLayoutStr(CGM, BlockInfo);
172 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
173 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
174 /// meta-data and contains stationary information about the block literal.
175 /// Its definition will have 4 (or optionally 6) words.
177 /// struct Block_descriptor {
178 /// unsigned long reserved;
179 /// unsigned long size; // size of Block_literal metadata in bytes.
180 /// void *copy_func_helper_decl; // optional copy helper.
181 /// void *destroy_func_decl; // optional destructor helper.
182 /// void *block_method_encoding_address; // @encode for block literal signature.
183 /// void *block_layout_info; // encoding of captured block variables.
186 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
187 const CGBlockInfo &blockInfo) {
188 ASTContext &C = CGM.getContext();
190 llvm::IntegerType *ulong =
191 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
192 llvm::PointerType *i8p = nullptr;
193 if (CGM.getLangOpts().OpenCL)
195 llvm::Type::getInt8PtrTy(
196 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
200 std::string descName;
202 // If an equivalent block descriptor global variable exists, return it.
203 if (C.getLangOpts().ObjC &&
204 CGM.getLangOpts().getGC() == LangOptions::NonGC) {
205 descName = getBlockDescriptorName(blockInfo, CGM);
206 if (llvm::GlobalValue *desc = CGM.getModule().getNamedValue(descName))
207 return llvm::ConstantExpr::getBitCast(desc,
208 CGM.getBlockDescriptorType());
211 // If there isn't an equivalent block descriptor global variable, create a new
213 ConstantInitBuilder builder(CGM);
214 auto elements = builder.beginStruct();
217 elements.addInt(ulong, 0);
220 // FIXME: What is the right way to say this doesn't fit? We should give
221 // a user diagnostic in that case. Better fix would be to change the
223 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
225 // Optional copy/dispose helpers.
226 bool hasInternalHelper = false;
227 if (blockInfo.needsCopyDisposeHelpers()) {
228 // copy_func_helper_decl
229 llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
230 elements.add(copyHelper);
233 llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
234 elements.add(disposeHelper);
236 if (cast<llvm::Function>(copyHelper->getOperand(0))->hasInternalLinkage() ||
237 cast<llvm::Function>(disposeHelper->getOperand(0))
238 ->hasInternalLinkage())
239 hasInternalHelper = true;
242 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
243 std::string typeAtEncoding =
244 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
245 elements.add(llvm::ConstantExpr::getBitCast(
246 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
249 if (C.getLangOpts().ObjC) {
250 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
251 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
253 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
256 elements.addNullPointer(i8p);
258 unsigned AddrSpace = 0;
259 if (C.getLangOpts().OpenCL)
260 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
262 llvm::GlobalValue::LinkageTypes linkage;
263 if (descName.empty()) {
264 linkage = llvm::GlobalValue::InternalLinkage;
265 descName = "__block_descriptor_tmp";
266 } else if (hasInternalHelper) {
267 // If either the copy helper or the dispose helper has internal linkage,
268 // the block descriptor must have internal linkage too.
269 linkage = llvm::GlobalValue::InternalLinkage;
271 linkage = llvm::GlobalValue::LinkOnceODRLinkage;
274 llvm::GlobalVariable *global =
275 elements.finishAndCreateGlobal(descName, CGM.getPointerAlign(),
276 /*constant*/ true, linkage, AddrSpace);
278 if (linkage == llvm::GlobalValue::LinkOnceODRLinkage) {
279 global->setVisibility(llvm::GlobalValue::HiddenVisibility);
280 global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
283 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
287 Purely notional variadic template describing the layout of a block.
289 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
290 struct Block_literal {
291 /// Initialized to one of:
292 /// extern void *_NSConcreteStackBlock[];
293 /// extern void *_NSConcreteGlobalBlock[];
295 /// In theory, we could start one off malloc'ed by setting
296 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
298 /// extern void *_NSConcreteMallocBlock[];
299 struct objc_class *isa;
301 /// These are the flags (with corresponding bit number) that the
302 /// compiler is actually supposed to know about.
303 /// 23. BLOCK_IS_NOESCAPE - indicates that the block is non-escaping
304 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
305 /// descriptor provides copy and dispose helper functions
306 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
307 /// object with a nontrivial destructor or copy constructor
308 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
310 /// 29. BLOCK_USE_STRET - indicates that the block function
311 /// uses stret, which objc_msgSend needs to know about
312 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
313 /// @encoded signature string
314 /// And we're not supposed to manipulate these:
315 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
316 /// to malloc'ed memory
317 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
318 /// to GC-allocated memory
319 /// Additionally, the bottom 16 bits are a reference count which
320 /// should be zero on the stack.
323 /// Reserved; should be zero-initialized.
326 /// Function pointer generated from block literal.
327 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
329 /// Block description metadata generated from block literal.
330 struct Block_descriptor *block_descriptor;
332 /// Captured values follow.
333 _CapturesTypes captures...;
338 /// A chunk of data that we actually have to capture in the block.
339 struct BlockLayoutChunk {
342 Qualifiers::ObjCLifetime Lifetime;
343 const BlockDecl::Capture *Capture; // null for 'this'
347 BlockLayoutChunk(CharUnits align, CharUnits size,
348 Qualifiers::ObjCLifetime lifetime,
349 const BlockDecl::Capture *capture,
350 llvm::Type *type, QualType fieldType)
351 : Alignment(align), Size(size), Lifetime(lifetime),
352 Capture(capture), Type(type), FieldType(fieldType) {}
354 /// Tell the block info that this chunk has the given field index.
355 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
357 info.CXXThisIndex = index;
358 info.CXXThisOffset = offset;
360 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
361 info.Captures.insert({Capture->getVariable(), C});
366 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
367 /// all __weak together. Preserve descending alignment in all situations.
368 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
369 if (left.Alignment != right.Alignment)
370 return left.Alignment > right.Alignment;
372 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
373 if (chunk.Capture && chunk.Capture->isByRef())
375 if (chunk.Lifetime == Qualifiers::OCL_Strong)
377 if (chunk.Lifetime == Qualifiers::OCL_Weak)
382 return getPrefOrder(left) < getPrefOrder(right);
384 } // end anonymous namespace
386 /// Determines if the given type is safe for constant capture in C++.
387 static bool isSafeForCXXConstantCapture(QualType type) {
388 const RecordType *recordType =
389 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
391 // Only records can be unsafe.
392 if (!recordType) return true;
394 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
396 // Maintain semantics for classes with non-trivial dtors or copy ctors.
397 if (!record->hasTrivialDestructor()) return false;
398 if (record->hasNonTrivialCopyConstructor()) return false;
400 // Otherwise, we just have to make sure there aren't any mutable
401 // fields that might have changed since initialization.
402 return !record->hasMutableFields();
405 /// It is illegal to modify a const object after initialization.
406 /// Therefore, if a const object has a constant initializer, we don't
407 /// actually need to keep storage for it in the block; we'll just
408 /// rematerialize it at the start of the block function. This is
409 /// acceptable because we make no promises about address stability of
410 /// captured variables.
411 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
412 CodeGenFunction *CGF,
413 const VarDecl *var) {
414 // Return if this is a function parameter. We shouldn't try to
415 // rematerialize default arguments of function parameters.
416 if (isa<ParmVarDecl>(var))
419 QualType type = var->getType();
421 // We can only do this if the variable is const.
422 if (!type.isConstQualified()) return nullptr;
424 // Furthermore, in C++ we have to worry about mutable fields:
425 // C++ [dcl.type.cv]p4:
426 // Except that any class member declared mutable can be
427 // modified, any attempt to modify a const object during its
428 // lifetime results in undefined behavior.
429 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
432 // If the variable doesn't have any initializer (shouldn't this be
433 // invalid?), it's not clear what we should do. Maybe capture as
435 const Expr *init = var->getInit();
436 if (!init) return nullptr;
438 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
441 /// Get the low bit of a nonzero character count. This is the
442 /// alignment of the nth byte if the 0th byte is universally aligned.
443 static CharUnits getLowBit(CharUnits v) {
444 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
447 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
448 SmallVectorImpl<llvm::Type*> &elementTypes) {
450 assert(elementTypes.empty());
451 if (CGM.getLangOpts().OpenCL) {
452 // The header is basically 'struct { int; int; generic void *;
453 // custom_fields; }'. Assert that struct is packed.
455 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic);
457 CharUnits::fromQuantity(CGM.getTarget().getPointerAlign(GenericAS) / 8);
459 CharUnits::fromQuantity(CGM.getTarget().getPointerWidth(GenericAS) / 8);
460 assert(CGM.getIntSize() <= GenPtrSize);
461 assert(CGM.getIntAlign() <= GenPtrAlign);
462 assert((2 * CGM.getIntSize()).isMultipleOf(GenPtrAlign));
463 elementTypes.push_back(CGM.IntTy); /* total size */
464 elementTypes.push_back(CGM.IntTy); /* align */
465 elementTypes.push_back(
466 CGM.getOpenCLRuntime()
467 .getGenericVoidPointerType()); /* invoke function */
469 2 * CGM.getIntSize().getQuantity() + GenPtrSize.getQuantity();
470 unsigned BlockAlign = GenPtrAlign.getQuantity();
472 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
473 for (auto I : Helper->getCustomFieldTypes()) /* custom fields */ {
474 // TargetOpenCLBlockHelp needs to make sure the struct is packed.
475 // If necessary, add padding fields to the custom fields.
476 unsigned Align = CGM.getDataLayout().getABITypeAlignment(I);
477 if (BlockAlign < Align)
479 assert(Offset % Align == 0);
480 Offset += CGM.getDataLayout().getTypeAllocSize(I);
481 elementTypes.push_back(I);
484 info.BlockAlign = CharUnits::fromQuantity(BlockAlign);
485 info.BlockSize = CharUnits::fromQuantity(Offset);
487 // The header is basically 'struct { void *; int; int; void *; void *; }'.
488 // Assert that the struct is packed.
489 assert(CGM.getIntSize() <= CGM.getPointerSize());
490 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
491 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
492 info.BlockAlign = CGM.getPointerAlign();
493 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
494 elementTypes.push_back(CGM.VoidPtrTy);
495 elementTypes.push_back(CGM.IntTy);
496 elementTypes.push_back(CGM.IntTy);
497 elementTypes.push_back(CGM.VoidPtrTy);
498 elementTypes.push_back(CGM.getBlockDescriptorType());
502 static QualType getCaptureFieldType(const CodeGenFunction &CGF,
503 const BlockDecl::Capture &CI) {
504 const VarDecl *VD = CI.getVariable();
506 // If the variable is captured by an enclosing block or lambda expression,
507 // use the type of the capture field.
508 if (CGF.BlockInfo && CI.isNested())
509 return CGF.BlockInfo->getCapture(VD).fieldType();
510 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
511 return FD->getType();
512 // If the captured variable is a non-escaping __block variable, the field
513 // type is the reference type. If the variable is a __block variable that
514 // already has a reference type, the field type is the variable's type.
515 return VD->isNonEscapingByref() ?
516 CGF.getContext().getLValueReferenceType(VD->getType()) : VD->getType();
519 /// Compute the layout of the given block. Attempts to lay the block
520 /// out with minimal space requirements.
521 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
523 ASTContext &C = CGM.getContext();
524 const BlockDecl *block = info.getBlockDecl();
526 SmallVector<llvm::Type*, 8> elementTypes;
527 initializeForBlockHeader(CGM, info, elementTypes);
528 bool hasNonConstantCustomFields = false;
529 if (auto *OpenCLHelper =
530 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper())
531 hasNonConstantCustomFields =
532 !OpenCLHelper->areAllCustomFieldValuesConstant(info);
533 if (!block->hasCaptures() && !hasNonConstantCustomFields) {
535 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
536 info.CanBeGlobal = true;
539 else if (C.getLangOpts().ObjC &&
540 CGM.getLangOpts().getGC() == LangOptions::NonGC)
541 info.HasCapturedVariableLayout = true;
543 // Collect the layout chunks.
544 SmallVector<BlockLayoutChunk, 16> layout;
545 layout.reserve(block->capturesCXXThis() +
546 (block->capture_end() - block->capture_begin()));
548 CharUnits maxFieldAlign;
551 if (block->capturesCXXThis()) {
552 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
553 "Can't capture 'this' outside a method");
554 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType();
556 // Theoretically, this could be in a different address space, so
557 // don't assume standard pointer size/align.
558 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
559 std::pair<CharUnits,CharUnits> tinfo
560 = CGM.getContext().getTypeInfoInChars(thisType);
561 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
563 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
564 Qualifiers::OCL_None,
565 nullptr, llvmType, thisType));
568 // Next, all the block captures.
569 for (const auto &CI : block->captures()) {
570 const VarDecl *variable = CI.getVariable();
572 if (CI.isEscapingByref()) {
573 // We have to copy/dispose of the __block reference.
574 info.NeedsCopyDispose = true;
576 // Just use void* instead of a pointer to the byref type.
577 CharUnits align = CGM.getPointerAlign();
578 maxFieldAlign = std::max(maxFieldAlign, align);
580 // Since a __block variable cannot be captured by lambdas, its type and
581 // the capture field type should always match.
582 assert(getCaptureFieldType(*CGF, CI) == variable->getType() &&
583 "capture type differs from the variable type");
584 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
585 Qualifiers::OCL_None, &CI,
586 CGM.VoidPtrTy, variable->getType()));
590 // Otherwise, build a layout chunk with the size and alignment of
592 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
593 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
597 QualType VT = getCaptureFieldType(*CGF, CI);
599 // If we have a lifetime qualifier, honor it for capture purposes.
600 // That includes *not* copying it if it's __unsafe_unretained.
601 Qualifiers::ObjCLifetime lifetime = VT.getObjCLifetime();
604 case Qualifiers::OCL_None: llvm_unreachable("impossible");
605 case Qualifiers::OCL_ExplicitNone:
606 case Qualifiers::OCL_Autoreleasing:
609 case Qualifiers::OCL_Strong:
610 case Qualifiers::OCL_Weak:
611 info.NeedsCopyDispose = true;
614 // Block pointers require copy/dispose. So do Objective-C pointers.
615 } else if (VT->isObjCRetainableType()) {
616 // But honor the inert __unsafe_unretained qualifier, which doesn't
617 // actually make it into the type system.
618 if (VT->isObjCInertUnsafeUnretainedType()) {
619 lifetime = Qualifiers::OCL_ExplicitNone;
621 info.NeedsCopyDispose = true;
622 // used for mrr below.
623 lifetime = Qualifiers::OCL_Strong;
626 // So do types that require non-trivial copy construction.
627 } else if (CI.hasCopyExpr()) {
628 info.NeedsCopyDispose = true;
629 info.HasCXXObject = true;
630 if (!VT->getAsCXXRecordDecl()->isExternallyVisible())
631 info.CapturesNonExternalType = true;
633 // So do C structs that require non-trivial copy construction or
635 } else if (VT.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct ||
636 VT.isDestructedType() == QualType::DK_nontrivial_c_struct) {
637 info.NeedsCopyDispose = true;
639 // And so do types with destructors.
640 } else if (CGM.getLangOpts().CPlusPlus) {
641 if (const CXXRecordDecl *record = VT->getAsCXXRecordDecl()) {
642 if (!record->hasTrivialDestructor()) {
643 info.HasCXXObject = true;
644 info.NeedsCopyDispose = true;
645 if (!record->isExternallyVisible())
646 info.CapturesNonExternalType = true;
651 CharUnits size = C.getTypeSizeInChars(VT);
652 CharUnits align = C.getDeclAlign(variable);
654 maxFieldAlign = std::max(maxFieldAlign, align);
656 llvm::Type *llvmType =
657 CGM.getTypes().ConvertTypeForMem(VT);
660 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
663 // If that was everything, we're done here.
664 if (layout.empty()) {
666 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
667 info.CanBeGlobal = true;
671 // Sort the layout by alignment. We have to use a stable sort here
672 // to get reproducible results. There should probably be an
673 // llvm::array_pod_stable_sort.
674 std::stable_sort(layout.begin(), layout.end());
676 // Needed for blocks layout info.
677 info.BlockHeaderForcedGapOffset = info.BlockSize;
678 info.BlockHeaderForcedGapSize = CharUnits::Zero();
680 CharUnits &blockSize = info.BlockSize;
681 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
683 // Assuming that the first byte in the header is maximally aligned,
684 // get the alignment of the first byte following the header.
685 CharUnits endAlign = getLowBit(blockSize);
687 // If the end of the header isn't satisfactorily aligned for the
688 // maximum thing, look for things that are okay with the header-end
689 // alignment, and keep appending them until we get something that's
690 // aligned right. This algorithm is only guaranteed optimal if
691 // that condition is satisfied at some point; otherwise we can get
693 // header // next byte has alignment 4
694 // something_with_size_5; // next byte has alignment 1
695 // something_with_alignment_8;
696 // which has 7 bytes of padding, as opposed to the naive solution
697 // which might have less (?).
698 if (endAlign < maxFieldAlign) {
699 SmallVectorImpl<BlockLayoutChunk>::iterator
700 li = layout.begin() + 1, le = layout.end();
702 // Look for something that the header end is already
703 // satisfactorily aligned for.
704 for (; li != le && endAlign < li->Alignment; ++li)
707 // If we found something that's naturally aligned for the end of
708 // the header, keep adding things...
710 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
711 for (; li != le; ++li) {
712 assert(endAlign >= li->Alignment);
714 li->setIndex(info, elementTypes.size(), blockSize);
715 elementTypes.push_back(li->Type);
716 blockSize += li->Size;
717 endAlign = getLowBit(blockSize);
719 // ...until we get to the alignment of the maximum field.
720 if (endAlign >= maxFieldAlign) {
724 // Don't re-append everything we just appended.
725 layout.erase(first, li);
729 assert(endAlign == getLowBit(blockSize));
731 // At this point, we just have to add padding if the end align still
732 // isn't aligned right.
733 if (endAlign < maxFieldAlign) {
734 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
735 CharUnits padding = newBlockSize - blockSize;
737 // If we haven't yet added any fields, remember that there was an
738 // initial gap; this need to go into the block layout bit map.
739 if (blockSize == info.BlockHeaderForcedGapOffset) {
740 info.BlockHeaderForcedGapSize = padding;
743 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
744 padding.getQuantity()));
745 blockSize = newBlockSize;
746 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
749 assert(endAlign >= maxFieldAlign);
750 assert(endAlign == getLowBit(blockSize));
751 // Slam everything else on now. This works because they have
752 // strictly decreasing alignment and we expect that size is always a
753 // multiple of alignment.
754 for (SmallVectorImpl<BlockLayoutChunk>::iterator
755 li = layout.begin(), le = layout.end(); li != le; ++li) {
756 if (endAlign < li->Alignment) {
757 // size may not be multiple of alignment. This can only happen with
758 // an over-aligned variable. We will be adding a padding field to
759 // make the size be multiple of alignment.
760 CharUnits padding = li->Alignment - endAlign;
761 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
762 padding.getQuantity()));
763 blockSize += padding;
764 endAlign = getLowBit(blockSize);
766 assert(endAlign >= li->Alignment);
767 li->setIndex(info, elementTypes.size(), blockSize);
768 elementTypes.push_back(li->Type);
769 blockSize += li->Size;
770 endAlign = getLowBit(blockSize);
774 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
777 /// Enter the scope of a block. This should be run at the entrance to
778 /// a full-expression so that the block's cleanups are pushed at the
779 /// right place in the stack.
780 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
781 assert(CGF.HaveInsertPoint());
783 // Allocate the block info and place it at the head of the list.
784 CGBlockInfo &blockInfo =
785 *new CGBlockInfo(block, CGF.CurFn->getName());
786 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
787 CGF.FirstBlockInfo = &blockInfo;
789 // Compute information about the layout, etc., of this block,
790 // pushing cleanups as necessary.
791 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
793 // Nothing else to do if it can be global.
794 if (blockInfo.CanBeGlobal) return;
796 // Make the allocation for the block.
797 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
798 blockInfo.BlockAlign, "block");
800 // If there are cleanups to emit, enter them (but inactive).
801 if (!blockInfo.NeedsCopyDispose) return;
803 // Walk through the captures (in order) and find the ones not
804 // captured by constant.
805 for (const auto &CI : block->captures()) {
806 // Ignore __block captures; there's nothing special in the
807 // on-stack block that we need to do for them.
808 if (CI.isByRef()) continue;
810 // Ignore variables that are constant-captured.
811 const VarDecl *variable = CI.getVariable();
812 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
813 if (capture.isConstant()) continue;
815 // Ignore objects that aren't destructed.
816 QualType VT = getCaptureFieldType(CGF, CI);
817 QualType::DestructionKind dtorKind = VT.isDestructedType();
818 if (dtorKind == QualType::DK_none) continue;
820 CodeGenFunction::Destroyer *destroyer;
822 // Block captures count as local values and have imprecise semantics.
823 // They also can't be arrays, so need to worry about that.
825 // For const-qualified captures, emit clang.arc.use to ensure the captured
826 // object doesn't get released while we are still depending on its validity
828 if (VT.isConstQualified() &&
829 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
830 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
831 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
832 "expected ObjC ARC to be enabled");
833 destroyer = CodeGenFunction::emitARCIntrinsicUse;
834 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
835 destroyer = CodeGenFunction::destroyARCStrongImprecise;
837 destroyer = CGF.getDestroyer(dtorKind);
840 // GEP down to the address.
841 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
843 capture.getOffset());
845 // We can use that GEP as the dominating IP.
846 if (!blockInfo.DominatingIP)
847 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
849 CleanupKind cleanupKind = InactiveNormalCleanup;
850 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
851 if (useArrayEHCleanup)
852 cleanupKind = InactiveNormalAndEHCleanup;
854 CGF.pushDestroy(cleanupKind, addr, VT,
855 destroyer, useArrayEHCleanup);
857 // Remember where that cleanup was.
858 capture.setCleanup(CGF.EHStack.stable_begin());
862 /// Enter a full-expression with a non-trivial number of objects to
863 /// clean up. This is in this file because, at the moment, the only
864 /// kind of cleanup object is a BlockDecl*.
865 void CodeGenFunction::enterNonTrivialFullExpression(const FullExpr *E) {
866 if (const auto EWC = dyn_cast<ExprWithCleanups>(E)) {
867 assert(EWC->getNumObjects() != 0);
868 for (const ExprWithCleanups::CleanupObject &C : EWC->getObjects())
869 enterBlockScope(*this, C);
873 /// Find the layout for the given block in a linked list and remove it.
874 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
875 const BlockDecl *block) {
877 assert(head && *head);
878 CGBlockInfo *cur = *head;
880 // If this is the block we're looking for, splice it out of the list.
881 if (cur->getBlockDecl() == block) {
882 *head = cur->NextBlockInfo;
886 head = &cur->NextBlockInfo;
890 /// Destroy a chain of block layouts.
891 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
892 assert(head && "destroying an empty chain");
894 CGBlockInfo *cur = head;
895 head = cur->NextBlockInfo;
897 } while (head != nullptr);
900 /// Emit a block literal expression in the current function.
901 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
902 // If the block has no captures, we won't have a pre-computed
904 if (!blockExpr->getBlockDecl()->hasCaptures()) {
905 // The block literal is emitted as a global variable, and the block invoke
906 // function has to be extracted from its initializer.
907 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr)) {
910 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
911 computeBlockInfo(CGM, this, blockInfo);
912 blockInfo.BlockExpression = blockExpr;
913 return EmitBlockLiteral(blockInfo);
916 // Find the block info for this block and take ownership of it.
917 std::unique_ptr<CGBlockInfo> blockInfo;
918 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
919 blockExpr->getBlockDecl()));
921 blockInfo->BlockExpression = blockExpr;
922 return EmitBlockLiteral(*blockInfo);
925 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
926 bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
928 IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
929 LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
930 auto GenVoidPtrSize = CharUnits::fromQuantity(
931 CGM.getTarget().getPointerWidth(
932 CGM.getContext().getTargetAddressSpace(GenVoidPtrAddr)) /
934 // Using the computed layout, generate the actual block function.
935 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
936 CodeGenFunction BlockCGF{CGM, true};
937 BlockCGF.SanOpts = SanOpts;
938 auto *InvokeFn = BlockCGF.GenerateBlockFunction(
939 CurGD, blockInfo, LocalDeclMap, isLambdaConv, blockInfo.CanBeGlobal);
940 auto *blockFn = llvm::ConstantExpr::getPointerCast(InvokeFn, GenVoidPtrTy);
942 // If there is nothing to capture, we can emit this as a global block.
943 if (blockInfo.CanBeGlobal)
944 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
946 // Otherwise, we have to emit this as a local block.
948 Address blockAddr = blockInfo.LocalAddress;
949 assert(blockAddr.isValid() && "block has no address!");
952 llvm::Constant *descriptor;
955 // If the block is non-escaping, set field 'isa 'to NSConcreteGlobalBlock
956 // and set the BLOCK_IS_GLOBAL bit of field 'flags'. Copying a non-escaping
957 // block just returns the original block and releasing it is a no-op.
958 llvm::Constant *blockISA = blockInfo.getBlockDecl()->doesNotEscape()
959 ? CGM.getNSConcreteGlobalBlock()
960 : CGM.getNSConcreteStackBlock();
961 isa = llvm::ConstantExpr::getBitCast(blockISA, VoidPtrTy);
963 // Build the block descriptor.
964 descriptor = buildBlockDescriptor(CGM, blockInfo);
966 // Compute the initial on-stack block flags.
967 flags = BLOCK_HAS_SIGNATURE;
968 if (blockInfo.HasCapturedVariableLayout)
969 flags |= BLOCK_HAS_EXTENDED_LAYOUT;
970 if (blockInfo.needsCopyDisposeHelpers())
971 flags |= BLOCK_HAS_COPY_DISPOSE;
972 if (blockInfo.HasCXXObject)
973 flags |= BLOCK_HAS_CXX_OBJ;
974 if (blockInfo.UsesStret)
975 flags |= BLOCK_USE_STRET;
976 if (blockInfo.getBlockDecl()->doesNotEscape())
977 flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
981 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
982 return Builder.CreateStructGEP(blockAddr, index, offset, name);
985 [&](llvm::Value *value, unsigned index, CharUnits offset,
987 Builder.CreateStore(value, projectField(index, offset, name));
990 // Initialize the block header.
992 // We assume all the header fields are densely packed.
995 auto addHeaderField =
996 [&](llvm::Value *value, CharUnits size, const Twine &name) {
997 storeField(value, index, offset, name);
1003 addHeaderField(isa, getPointerSize(), "block.isa");
1004 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1005 getIntSize(), "block.flags");
1006 addHeaderField(llvm::ConstantInt::get(IntTy, 0), getIntSize(),
1010 llvm::ConstantInt::get(IntTy, blockInfo.BlockSize.getQuantity()),
1011 getIntSize(), "block.size");
1013 llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
1014 getIntSize(), "block.align");
1016 addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
1018 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
1019 else if (auto *Helper =
1020 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1021 for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
1024 CharUnits::fromQuantity(
1025 CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
1031 // Finally, capture all the values into the block.
1032 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1035 if (blockDecl->capturesCXXThis()) {
1036 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
1037 "block.captured-this.addr");
1038 Builder.CreateStore(LoadCXXThis(), addr);
1041 // Next, captured variables.
1042 for (const auto &CI : blockDecl->captures()) {
1043 const VarDecl *variable = CI.getVariable();
1044 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1046 // Ignore constant captures.
1047 if (capture.isConstant()) continue;
1049 QualType type = capture.fieldType();
1051 // This will be a [[type]]*, except that a byref entry will just be
1053 Address blockField =
1054 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
1056 // Compute the address of the thing we're going to move into the
1058 Address src = Address::invalid();
1060 if (blockDecl->isConversionFromLambda()) {
1061 // The lambda capture in a lambda's conversion-to-block-pointer is
1062 // special; we'll simply emit it directly.
1063 src = Address::invalid();
1064 } else if (CI.isEscapingByref()) {
1065 if (BlockInfo && CI.isNested()) {
1066 // We need to use the capture from the enclosing block.
1067 const CGBlockInfo::Capture &enclosingCapture =
1068 BlockInfo->getCapture(variable);
1070 // This is a [[type]]*, except that a byref entry will just be an i8**.
1071 src = Builder.CreateStructGEP(LoadBlockStruct(),
1072 enclosingCapture.getIndex(),
1073 enclosingCapture.getOffset(),
1074 "block.capture.addr");
1076 auto I = LocalDeclMap.find(variable);
1077 assert(I != LocalDeclMap.end());
1081 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1082 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1083 type.getNonReferenceType(), VK_LValue,
1085 src = EmitDeclRefLValue(&declRef).getAddress();
1088 // For byrefs, we just write the pointer to the byref struct into
1089 // the block field. There's no need to chase the forwarding
1090 // pointer at this point, since we're building something that will
1091 // live a shorter life than the stack byref anyway.
1092 if (CI.isEscapingByref()) {
1093 // Get a void* that points to the byref struct.
1094 llvm::Value *byrefPointer;
1096 byrefPointer = Builder.CreateLoad(src, "byref.capture");
1098 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
1100 // Write that void* into the capture field.
1101 Builder.CreateStore(byrefPointer, blockField);
1103 // If we have a copy constructor, evaluate that into the block field.
1104 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
1105 if (blockDecl->isConversionFromLambda()) {
1106 // If we have a lambda conversion, emit the expression
1107 // directly into the block instead.
1109 AggValueSlot::forAddr(blockField, Qualifiers(),
1110 AggValueSlot::IsDestructed,
1111 AggValueSlot::DoesNotNeedGCBarriers,
1112 AggValueSlot::IsNotAliased,
1113 AggValueSlot::DoesNotOverlap);
1114 EmitAggExpr(copyExpr, Slot);
1116 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
1119 // If it's a reference variable, copy the reference into the block field.
1120 } else if (type->isReferenceType()) {
1121 Builder.CreateStore(src.getPointer(), blockField);
1123 // If type is const-qualified, copy the value into the block field.
1124 } else if (type.isConstQualified() &&
1125 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1126 CGM.getCodeGenOpts().OptimizationLevel != 0) {
1127 llvm::Value *value = Builder.CreateLoad(src, "captured");
1128 Builder.CreateStore(value, blockField);
1130 // If this is an ARC __strong block-pointer variable, don't do a
1133 // TODO: this can be generalized into the normal initialization logic:
1134 // we should never need to do a block-copy when initializing a local
1135 // variable, because the local variable's lifetime should be strictly
1136 // contained within the stack block's.
1137 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
1138 type->isBlockPointerType()) {
1139 // Load the block and do a simple retain.
1140 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
1141 value = EmitARCRetainNonBlock(value);
1143 // Do a primitive store to the block field.
1144 Builder.CreateStore(value, blockField);
1146 // Otherwise, fake up a POD copy into the block field.
1148 // Fake up a new variable so that EmitScalarInit doesn't think
1149 // we're referring to the variable in its own initializer.
1150 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
1151 ImplicitParamDecl::Other);
1153 // We use one of these or the other depending on whether the
1154 // reference is nested.
1155 DeclRefExpr declRef(getContext(), const_cast<VarDecl *>(variable),
1156 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
1157 type, VK_LValue, SourceLocation());
1159 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
1160 &declRef, VK_RValue);
1161 // FIXME: Pass a specific location for the expr init so that the store is
1162 // attributed to a reasonable location - otherwise it may be attributed to
1163 // locations of subexpressions in the initialization.
1164 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
1165 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
1166 /*captured by init*/ false);
1169 // Activate the cleanup if layout pushed one.
1170 if (!CI.isByRef()) {
1171 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
1172 if (cleanup.isValid())
1173 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
1177 // Cast to the converted block-pointer type, which happens (somewhat
1178 // unfortunately) to be a pointer to function type.
1179 llvm::Value *result = Builder.CreatePointerCast(
1180 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
1183 CGM.getOpenCLRuntime().recordBlockInfo(blockInfo.BlockExpression, InvokeFn,
1191 llvm::Type *CodeGenModule::getBlockDescriptorType() {
1192 if (BlockDescriptorType)
1193 return BlockDescriptorType;
1195 llvm::Type *UnsignedLongTy =
1196 getTypes().ConvertType(getContext().UnsignedLongTy);
1198 // struct __block_descriptor {
1199 // unsigned long reserved;
1200 // unsigned long block_size;
1202 // // later, the following will be added
1205 // void (*copyHelper)();
1206 // void (*copyHelper)();
1207 // } helpers; // !!! optional
1209 // const char *signature; // the block signature
1210 // const char *layout; // reserved
1212 BlockDescriptorType = llvm::StructType::create(
1213 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
1215 // Now form a pointer to that.
1216 unsigned AddrSpace = 0;
1217 if (getLangOpts().OpenCL)
1218 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
1219 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
1220 return BlockDescriptorType;
1223 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
1224 if (GenericBlockLiteralType)
1225 return GenericBlockLiteralType;
1227 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
1229 if (getLangOpts().OpenCL) {
1230 // struct __opencl_block_literal_generic {
1233 // __generic void *__invoke;
1234 // /* custom fields */
1236 SmallVector<llvm::Type *, 8> StructFields(
1237 {IntTy, IntTy, getOpenCLRuntime().getGenericVoidPointerType()});
1238 if (auto *Helper = getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1239 for (auto I : Helper->getCustomFieldTypes())
1240 StructFields.push_back(I);
1242 GenericBlockLiteralType = llvm::StructType::create(
1243 StructFields, "struct.__opencl_block_literal_generic");
1245 // struct __block_literal_generic {
1249 // void (*__invoke)(void *);
1250 // struct __block_descriptor *__descriptor;
1252 GenericBlockLiteralType =
1253 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
1254 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
1257 return GenericBlockLiteralType;
1260 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
1261 ReturnValueSlot ReturnValue) {
1262 const BlockPointerType *BPT =
1263 E->getCallee()->getType()->getAs<BlockPointerType>();
1265 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
1267 // Get a pointer to the generic block literal.
1268 // For OpenCL we generate generic AS void ptr to be able to reuse the same
1269 // block definition for blocks with captures generated as private AS local
1270 // variables and without captures generated as global AS program scope
1272 unsigned AddrSpace = 0;
1273 if (getLangOpts().OpenCL)
1274 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1276 llvm::Type *BlockLiteralTy =
1277 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
1279 // Bitcast the callee to a block literal.
1281 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
1283 // Get the function pointer from the literal.
1284 llvm::Value *FuncPtr =
1285 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr,
1286 CGM.getLangOpts().OpenCL ? 2 : 3);
1288 // Add the block literal.
1291 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1292 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1293 if (getLangOpts().OpenCL) {
1294 GenericVoidPtrTy = CGM.getOpenCLRuntime().getGenericVoidPointerType();
1296 getContext().getPointerType(getContext().getAddrSpaceQualType(
1297 getContext().VoidTy, LangAS::opencl_generic));
1300 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1301 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
1303 QualType FnType = BPT->getPointeeType();
1305 // And the rest of the arguments.
1306 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
1308 // Load the function.
1309 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
1311 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
1312 const CGFunctionInfo &FnInfo =
1313 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1315 // Cast the function pointer to the right type.
1316 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1318 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1319 Func = Builder.CreatePointerCast(Func, BlockFTyPtr);
1321 // Prepare the callee.
1322 CGCallee Callee(CGCalleeInfo(), Func);
1324 // And call the block.
1325 return EmitCall(FnInfo, Callee, ReturnValue, Args);
1328 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable) {
1329 assert(BlockInfo && "evaluating block ref without block information?");
1330 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1332 // Handle constant captures.
1333 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1336 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1337 capture.getOffset(), "block.capture.addr");
1339 if (variable->isEscapingByref()) {
1340 // addr should be a void** right now. Load, then cast the result
1343 auto &byrefInfo = getBlockByrefInfo(variable);
1344 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1346 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1347 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1349 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1350 variable->getName());
1353 assert((!variable->isNonEscapingByref() ||
1354 capture.fieldType()->isReferenceType()) &&
1355 "the capture field of a non-escaping variable should have a "
1357 if (capture.fieldType()->isReferenceType())
1358 addr = EmitLoadOfReference(MakeAddrLValue(addr, capture.fieldType()));
1363 void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1364 llvm::Constant *Addr) {
1365 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1367 assert(Ok && "Trying to replace an already-existing global block!");
1371 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1373 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1376 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1377 blockInfo.BlockExpression = BE;
1379 // Compute information about the layout, etc., of this block.
1380 computeBlockInfo(*this, nullptr, blockInfo);
1382 // Using that metadata, generate the actual block function.
1384 CodeGenFunction::DeclMapTy LocalDeclMap;
1385 CodeGenFunction(*this).GenerateBlockFunction(
1386 GlobalDecl(), blockInfo, LocalDeclMap,
1387 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
1390 return getAddrOfGlobalBlockIfEmitted(BE);
1393 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1394 const CGBlockInfo &blockInfo,
1395 llvm::Constant *blockFn) {
1396 assert(blockInfo.CanBeGlobal);
1397 // Callers should detect this case on their own: calling this function
1398 // generally requires computing layout information, which is a waste of time
1399 // if we've already emitted this block.
1400 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1401 "Refusing to re-emit a global block.");
1403 // Generate the constants for the block literal initializer.
1404 ConstantInitBuilder builder(CGM);
1405 auto fields = builder.beginStruct();
1407 bool IsOpenCL = CGM.getLangOpts().OpenCL;
1408 bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
1412 fields.addNullPointer(CGM.Int8PtrPtrTy);
1414 fields.add(CGM.getNSConcreteGlobalBlock());
1417 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1418 if (blockInfo.UsesStret)
1419 flags |= BLOCK_USE_STRET;
1421 fields.addInt(CGM.IntTy, flags.getBitMask());
1424 fields.addInt(CGM.IntTy, 0);
1426 fields.addInt(CGM.IntTy, blockInfo.BlockSize.getQuantity());
1427 fields.addInt(CGM.IntTy, blockInfo.BlockAlign.getQuantity());
1431 fields.add(blockFn);
1435 fields.add(buildBlockDescriptor(CGM, blockInfo));
1436 } else if (auto *Helper =
1437 CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
1438 for (auto I : Helper->getCustomFieldValues(CGM, blockInfo)) {
1443 unsigned AddrSpace = 0;
1444 if (CGM.getContext().getLangOpts().OpenCL)
1445 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1447 llvm::Constant *literal = fields.finishAndCreateGlobal(
1448 "__block_literal_global", blockInfo.BlockAlign,
1449 /*constant*/ !IsWindows, llvm::GlobalVariable::InternalLinkage, AddrSpace);
1451 // Windows does not allow globals to be initialised to point to globals in
1452 // different DLLs. Any such variables must run code to initialise them.
1454 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1455 {}), llvm::GlobalValue::InternalLinkage, ".block_isa_init",
1457 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1459 b.CreateAlignedStore(CGM.getNSConcreteGlobalBlock(),
1460 b.CreateStructGEP(literal, 0), CGM.getPointerAlign().getQuantity());
1462 // We can't use the normal LLVM global initialisation array, because we
1463 // need to specify that this runs early in library initialisation.
1464 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1465 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1466 Init, ".block_isa_init_ptr");
1467 InitVar->setSection(".CRT$XCLa");
1468 CGM.addUsedGlobal(InitVar);
1471 // Return a constant of the appropriately-casted type.
1472 llvm::Type *RequiredType =
1473 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1474 llvm::Constant *Result =
1475 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
1476 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1477 if (CGM.getContext().getLangOpts().OpenCL)
1478 CGM.getOpenCLRuntime().recordBlockInfo(
1479 blockInfo.BlockExpression,
1480 cast<llvm::Function>(blockFn->stripPointerCasts()), Result);
1484 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1487 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1489 // Allocate a stack slot like for any local variable to guarantee optimal
1490 // debug info at -O0. The mem2reg pass will eliminate it when optimizing.
1491 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1492 Builder.CreateStore(arg, alloc);
1493 if (CGDebugInfo *DI = getDebugInfo()) {
1494 if (CGM.getCodeGenOpts().getDebugInfo() >=
1495 codegenoptions::LimitedDebugInfo) {
1496 DI->setLocation(D->getLocation());
1497 DI->EmitDeclareOfBlockLiteralArgVariable(
1498 *BlockInfo, D->getName(), argNum,
1499 cast<llvm::AllocaInst>(alloc.getPointer()), Builder);
1503 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getBeginLoc();
1504 ApplyDebugLocation Scope(*this, StartLoc);
1506 // Instead of messing around with LocalDeclMap, just set the value
1507 // directly as BlockPointer.
1508 BlockPointer = Builder.CreatePointerCast(
1510 BlockInfo->StructureType->getPointerTo(
1511 getContext().getLangOpts().OpenCL
1512 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1517 Address CodeGenFunction::LoadBlockStruct() {
1518 assert(BlockInfo && "not in a block invocation function!");
1519 assert(BlockPointer && "no block pointer set!");
1520 return Address(BlockPointer, BlockInfo->BlockAlign);
1524 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1525 const CGBlockInfo &blockInfo,
1526 const DeclMapTy &ldm,
1527 bool IsLambdaConversionToBlock,
1528 bool BuildGlobalBlock) {
1529 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1533 CurEHLocation = blockInfo.getBlockExpr()->getEndLoc();
1535 BlockInfo = &blockInfo;
1537 // Arrange for local static and local extern declarations to appear
1538 // to be local to this function as well, in case they're directly
1539 // referenced in a block.
1540 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1541 const auto *var = dyn_cast<VarDecl>(i->first);
1542 if (var && !var->hasLocalStorage())
1543 setAddrOfLocalVar(var, i->second);
1546 // Begin building the function declaration.
1548 // Build the argument list.
1549 FunctionArgList args;
1551 // The first argument is the block pointer. Just take it as a void*
1552 // and cast it later.
1553 QualType selfTy = getContext().VoidPtrTy;
1555 // For OpenCL passed block pointer can be private AS local variable or
1556 // global AS program scope variable (for the case with and without captures).
1557 // Generic AS is used therefore to be able to accommodate both private and
1558 // generic AS in one implementation.
1559 if (getLangOpts().OpenCL)
1560 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1561 getContext().VoidTy, LangAS::opencl_generic));
1563 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1565 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1566 SourceLocation(), II, selfTy,
1567 ImplicitParamDecl::ObjCSelf);
1568 args.push_back(&SelfDecl);
1570 // Now add the rest of the parameters.
1571 args.append(blockDecl->param_begin(), blockDecl->param_end());
1573 // Create the function declaration.
1574 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1575 const CGFunctionInfo &fnInfo =
1576 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1577 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1578 blockInfo.UsesStret = true;
1580 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1582 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1583 llvm::Function *fn = llvm::Function::Create(
1584 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1585 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1587 if (BuildGlobalBlock) {
1588 auto GenVoidPtrTy = getContext().getLangOpts().OpenCL
1589 ? CGM.getOpenCLRuntime().getGenericVoidPointerType()
1591 buildGlobalBlock(CGM, blockInfo,
1592 llvm::ConstantExpr::getPointerCast(fn, GenVoidPtrTy));
1595 // Begin generating the function.
1596 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1597 blockDecl->getLocation(),
1598 blockInfo.getBlockExpr()->getBody()->getBeginLoc());
1600 // Okay. Undo some of what StartFunction did.
1602 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1603 // won't delete the dbg.declare intrinsics for captured variables.
1604 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1605 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1606 // Allocate a stack slot for it, so we can point the debugger to it
1607 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1610 // Set the DebugLocation to empty, so the store is recognized as a
1611 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1612 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1613 Builder.CreateStore(BlockPointer, Alloca);
1614 BlockPointerDbgLoc = Alloca.getPointer();
1617 // If we have a C++ 'this' reference, go ahead and force it into
1619 if (blockDecl->capturesCXXThis()) {
1621 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1622 blockInfo.CXXThisOffset, "block.captured-this");
1623 CXXThisValue = Builder.CreateLoad(addr, "this");
1626 // Also force all the constant captures.
1627 for (const auto &CI : blockDecl->captures()) {
1628 const VarDecl *variable = CI.getVariable();
1629 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1630 if (!capture.isConstant()) continue;
1632 CharUnits align = getContext().getDeclAlign(variable);
1634 CreateMemTemp(variable->getType(), align, "block.captured-const");
1636 Builder.CreateStore(capture.getConstant(), alloca);
1638 setAddrOfLocalVar(variable, alloca);
1641 // Save a spot to insert the debug information for all the DeclRefExprs.
1642 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1643 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1646 if (IsLambdaConversionToBlock)
1647 EmitLambdaBlockInvokeBody();
1649 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1650 incrementProfileCounter(blockDecl->getBody());
1651 EmitStmt(blockDecl->getBody());
1654 // Remember where we were...
1655 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1657 // Go back to the entry.
1659 Builder.SetInsertPoint(entry, entry_ptr);
1661 // Emit debug information for all the DeclRefExprs.
1662 // FIXME: also for 'this'
1663 if (CGDebugInfo *DI = getDebugInfo()) {
1664 for (const auto &CI : blockDecl->captures()) {
1665 const VarDecl *variable = CI.getVariable();
1666 DI->EmitLocation(Builder, variable->getLocation());
1668 if (CGM.getCodeGenOpts().getDebugInfo() >=
1669 codegenoptions::LimitedDebugInfo) {
1670 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1671 if (capture.isConstant()) {
1672 auto addr = LocalDeclMap.find(variable)->second;
1673 (void)DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1678 DI->EmitDeclareOfBlockDeclRefVariable(
1679 variable, BlockPointerDbgLoc, Builder, blockInfo,
1680 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1683 // Recover location if it was changed in the above loop.
1684 DI->EmitLocation(Builder,
1685 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1688 // And resume where we left off.
1689 if (resume == nullptr)
1690 Builder.ClearInsertionPoint();
1692 Builder.SetInsertPoint(resume);
1694 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1699 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1700 computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1701 const LangOptions &LangOpts) {
1702 if (CI.getCopyExpr()) {
1703 assert(!CI.isByRef());
1704 // don't bother computing flags
1705 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1707 BlockFieldFlags Flags;
1708 if (CI.isEscapingByref()) {
1709 Flags = BLOCK_FIELD_IS_BYREF;
1710 if (T.isObjCGCWeak())
1711 Flags |= BLOCK_FIELD_IS_WEAK;
1712 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1715 Flags = BLOCK_FIELD_IS_OBJECT;
1716 bool isBlockPointer = T->isBlockPointerType();
1718 Flags = BLOCK_FIELD_IS_BLOCK;
1720 switch (T.isNonTrivialToPrimitiveCopy()) {
1721 case QualType::PCK_Struct:
1722 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
1724 case QualType::PCK_ARCWeak:
1725 // We need to register __weak direct captures with the runtime.
1726 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1727 case QualType::PCK_ARCStrong:
1728 // We need to retain the copied value for __strong direct captures.
1729 // If it's a block pointer, we have to copy the block and assign that to
1730 // the destination pointer, so we might as well use _Block_object_assign.
1731 // Otherwise we can avoid that.
1732 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1733 : BlockCaptureEntityKind::BlockObject,
1735 case QualType::PCK_Trivial:
1736 case QualType::PCK_VolatileTrivial: {
1737 if (!T->isObjCRetainableType())
1738 // For all other types, the memcpy is fine.
1739 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1741 // Special rules for ARC captures:
1742 Qualifiers QS = T.getQualifiers();
1744 // Non-ARC captures of retainable pointers are strong and
1745 // therefore require a call to _Block_object_assign.
1746 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1747 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1749 // Otherwise the memcpy is fine.
1750 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1753 llvm_unreachable("after exhaustive PrimitiveCopyKind switch");
1756 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1757 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1758 const LangOptions &LangOpts);
1760 /// Find the set of block captures that need to be explicitly copied or destroy.
1761 static void findBlockCapturedManagedEntities(
1762 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1763 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures) {
1764 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1765 const VarDecl *Variable = CI.getVariable();
1766 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1767 if (Capture.isConstant())
1770 QualType VT = Capture.fieldType();
1771 auto CopyInfo = computeCopyInfoForBlockCapture(CI, VT, LangOpts);
1772 auto DisposeInfo = computeDestroyInfoForBlockCapture(CI, VT, LangOpts);
1773 if (CopyInfo.first != BlockCaptureEntityKind::None ||
1774 DisposeInfo.first != BlockCaptureEntityKind::None)
1775 ManagedCaptures.emplace_back(CopyInfo.first, DisposeInfo.first,
1776 CopyInfo.second, DisposeInfo.second, CI,
1780 // Sort the captures by offset.
1781 llvm::sort(ManagedCaptures);
1785 /// Release a __block variable.
1786 struct CallBlockRelease final : EHScopeStack::Cleanup {
1788 BlockFieldFlags FieldFlags;
1789 bool LoadBlockVarAddr, CanThrow;
1791 CallBlockRelease(Address Addr, BlockFieldFlags Flags, bool LoadValue,
1793 : Addr(Addr), FieldFlags(Flags), LoadBlockVarAddr(LoadValue),
1796 void Emit(CodeGenFunction &CGF, Flags flags) override {
1797 llvm::Value *BlockVarAddr;
1798 if (LoadBlockVarAddr) {
1799 BlockVarAddr = CGF.Builder.CreateLoad(Addr);
1800 BlockVarAddr = CGF.Builder.CreateBitCast(BlockVarAddr, CGF.VoidPtrTy);
1802 BlockVarAddr = Addr.getPointer();
1805 CGF.BuildBlockRelease(BlockVarAddr, FieldFlags, CanThrow);
1808 } // end anonymous namespace
1810 /// Check if \p T is a C++ class that has a destructor that can throw.
1811 bool CodeGenFunction::cxxDestructorCanThrow(QualType T) {
1812 if (const auto *RD = T->getAsCXXRecordDecl())
1813 if (const CXXDestructorDecl *DD = RD->getDestructor())
1814 return DD->getType()->getAs<FunctionProtoType>()->canThrow();
1818 // Return a string that has the information about a capture.
1819 static std::string getBlockCaptureStr(const BlockCaptureManagedEntity &E,
1820 CaptureStrKind StrKind,
1821 CharUnits BlockAlignment,
1822 CodeGenModule &CGM) {
1824 ASTContext &Ctx = CGM.getContext();
1825 const BlockDecl::Capture &CI = *E.CI;
1826 QualType CaptureTy = CI.getVariable()->getType();
1828 BlockCaptureEntityKind Kind;
1829 BlockFieldFlags Flags;
1831 // CaptureStrKind::Merged should be passed only when the operations and the
1832 // flags are the same for copy and dispose.
1833 assert((StrKind != CaptureStrKind::Merged ||
1834 (E.CopyKind == E.DisposeKind && E.CopyFlags == E.DisposeFlags)) &&
1835 "different operations and flags");
1837 if (StrKind == CaptureStrKind::DisposeHelper) {
1838 Kind = E.DisposeKind;
1839 Flags = E.DisposeFlags;
1842 Flags = E.CopyFlags;
1846 case BlockCaptureEntityKind::CXXRecord: {
1848 SmallString<256> TyStr;
1849 llvm::raw_svector_ostream Out(TyStr);
1850 CGM.getCXXABI().getMangleContext().mangleTypeName(CaptureTy, Out);
1851 Str += llvm::to_string(TyStr.size()) + TyStr.c_str();
1854 case BlockCaptureEntityKind::ARCWeak:
1857 case BlockCaptureEntityKind::ARCStrong:
1860 case BlockCaptureEntityKind::BlockObject: {
1861 const VarDecl *Var = CI.getVariable();
1862 unsigned F = Flags.getBitMask();
1863 if (F & BLOCK_FIELD_IS_BYREF) {
1865 if (F & BLOCK_FIELD_IS_WEAK)
1868 // If CaptureStrKind::Merged is passed, check both the copy expression
1869 // and the destructor.
1870 if (StrKind != CaptureStrKind::DisposeHelper) {
1871 if (Ctx.getBlockVarCopyInit(Var).canThrow())
1874 if (StrKind != CaptureStrKind::CopyHelper) {
1875 if (CodeGenFunction::cxxDestructorCanThrow(CaptureTy))
1880 assert((F & BLOCK_FIELD_IS_OBJECT) && "unexpected flag value");
1881 if (F == BLOCK_FIELD_IS_BLOCK)
1888 case BlockCaptureEntityKind::NonTrivialCStruct: {
1889 bool IsVolatile = CaptureTy.isVolatileQualified();
1890 CharUnits Alignment =
1891 BlockAlignment.alignmentAtOffset(E.Capture->getOffset());
1894 std::string FuncStr;
1895 if (StrKind == CaptureStrKind::DisposeHelper)
1896 FuncStr = CodeGenFunction::getNonTrivialDestructorStr(
1897 CaptureTy, Alignment, IsVolatile, Ctx);
1899 // If CaptureStrKind::Merged is passed, use the copy constructor string.
1900 // It has all the information that the destructor string has.
1901 FuncStr = CodeGenFunction::getNonTrivialCopyConstructorStr(
1902 CaptureTy, Alignment, IsVolatile, Ctx);
1903 // The underscore is necessary here because non-trivial copy constructor
1904 // and destructor strings can start with a number.
1905 Str += llvm::to_string(FuncStr.size()) + "_" + FuncStr;
1908 case BlockCaptureEntityKind::None:
1915 static std::string getCopyDestroyHelperFuncName(
1916 const SmallVectorImpl<BlockCaptureManagedEntity> &Captures,
1917 CharUnits BlockAlignment, CaptureStrKind StrKind, CodeGenModule &CGM) {
1918 assert((StrKind == CaptureStrKind::CopyHelper ||
1919 StrKind == CaptureStrKind::DisposeHelper) &&
1920 "unexpected CaptureStrKind");
1921 std::string Name = StrKind == CaptureStrKind::CopyHelper
1922 ? "__copy_helper_block_"
1923 : "__destroy_helper_block_";
1924 if (CGM.getLangOpts().Exceptions)
1926 if (CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
1928 Name += llvm::to_string(BlockAlignment.getQuantity()) + "_";
1930 for (const BlockCaptureManagedEntity &E : Captures) {
1931 Name += llvm::to_string(E.Capture->getOffset().getQuantity());
1932 Name += getBlockCaptureStr(E, StrKind, BlockAlignment, CGM);
1938 static void pushCaptureCleanup(BlockCaptureEntityKind CaptureKind,
1939 Address Field, QualType CaptureType,
1940 BlockFieldFlags Flags, bool ForCopyHelper,
1941 VarDecl *Var, CodeGenFunction &CGF) {
1942 bool EHOnly = ForCopyHelper;
1944 switch (CaptureKind) {
1945 case BlockCaptureEntityKind::CXXRecord:
1946 case BlockCaptureEntityKind::ARCWeak:
1947 case BlockCaptureEntityKind::NonTrivialCStruct:
1948 case BlockCaptureEntityKind::ARCStrong: {
1949 if (CaptureType.isDestructedType() &&
1950 (!EHOnly || CGF.needsEHCleanup(CaptureType.isDestructedType()))) {
1951 CodeGenFunction::Destroyer *Destroyer =
1952 CaptureKind == BlockCaptureEntityKind::ARCStrong
1953 ? CodeGenFunction::destroyARCStrongImprecise
1954 : CGF.getDestroyer(CaptureType.isDestructedType());
1957 : CGF.getCleanupKind(CaptureType.isDestructedType());
1958 CGF.pushDestroy(Kind, Field, CaptureType, Destroyer, Kind & EHCleanup);
1962 case BlockCaptureEntityKind::BlockObject: {
1963 if (!EHOnly || CGF.getLangOpts().Exceptions) {
1964 CleanupKind Kind = EHOnly ? EHCleanup : NormalAndEHCleanup;
1965 // Calls to _Block_object_dispose along the EH path in the copy helper
1966 // function don't throw as newly-copied __block variables always have a
1967 // reference count of 2.
1969 !ForCopyHelper && CGF.cxxDestructorCanThrow(CaptureType);
1970 CGF.enterByrefCleanup(Kind, Field, Flags, /*LoadBlockVarAddr*/ true,
1975 case BlockCaptureEntityKind::None:
1980 static void setBlockHelperAttributesVisibility(bool CapturesNonExternalType,
1982 const CGFunctionInfo &FI,
1983 CodeGenModule &CGM) {
1984 if (CapturesNonExternalType) {
1985 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
1987 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1988 Fn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1989 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
1990 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1993 /// Generate the copy-helper function for a block closure object:
1994 /// static void block_copy_helper(block_t *dst, block_t *src);
1995 /// The runtime will have previously initialized 'dst' by doing a
1996 /// bit-copy of 'src'.
1998 /// Note that this copies an entire block closure object to the heap;
1999 /// it should not be confused with a 'byref copy helper', which moves
2000 /// the contents of an individual __block variable to the heap.
2002 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
2003 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
2004 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures);
2005 std::string FuncName =
2006 getCopyDestroyHelperFuncName(CopiedCaptures, blockInfo.BlockAlign,
2007 CaptureStrKind::CopyHelper, CGM);
2009 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2010 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2012 ASTContext &C = getContext();
2014 QualType ReturnTy = C.VoidTy;
2016 FunctionArgList args;
2017 ImplicitParamDecl DstDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2018 args.push_back(&DstDecl);
2019 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2020 args.push_back(&SrcDecl);
2022 const CGFunctionInfo &FI =
2023 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2025 // FIXME: it would be nice if these were mergeable with things with
2026 // identical semantics.
2027 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2029 llvm::Function *Fn =
2030 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2031 FuncName, &CGM.getModule());
2033 IdentifierInfo *II = &C.Idents.get(FuncName);
2035 SmallVector<QualType, 2> ArgTys;
2036 ArgTys.push_back(C.VoidPtrTy);
2037 ArgTys.push_back(C.VoidPtrTy);
2038 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2040 FunctionDecl *FD = FunctionDecl::Create(
2041 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2042 FunctionTy, nullptr, SC_Static, false, false);
2044 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2046 StartFunction(FD, ReturnTy, Fn, FI, args);
2047 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
2048 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2050 Address src = GetAddrOfLocalVar(&SrcDecl);
2051 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2052 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
2054 Address dst = GetAddrOfLocalVar(&DstDecl);
2055 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
2056 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
2058 for (const auto &CopiedCapture : CopiedCaptures) {
2059 const BlockDecl::Capture &CI = *CopiedCapture.CI;
2060 const CGBlockInfo::Capture &capture = *CopiedCapture.Capture;
2061 QualType captureType = CI.getVariable()->getType();
2062 BlockFieldFlags flags = CopiedCapture.CopyFlags;
2064 unsigned index = capture.getIndex();
2065 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
2066 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
2068 switch (CopiedCapture.CopyKind) {
2069 case BlockCaptureEntityKind::CXXRecord:
2070 // If there's an explicit copy expression, we do that.
2071 assert(CI.getCopyExpr() && "copy expression for variable is missing");
2072 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
2074 case BlockCaptureEntityKind::ARCWeak:
2075 EmitARCCopyWeak(dstField, srcField);
2077 case BlockCaptureEntityKind::NonTrivialCStruct: {
2078 // If this is a C struct that requires non-trivial copy construction,
2079 // emit a call to its copy constructor.
2080 QualType varType = CI.getVariable()->getType();
2081 callCStructCopyConstructor(MakeAddrLValue(dstField, varType),
2082 MakeAddrLValue(srcField, varType));
2085 case BlockCaptureEntityKind::ARCStrong: {
2086 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2087 // At -O0, store null into the destination field (so that the
2088 // storeStrong doesn't over-release) and then call storeStrong.
2089 // This is a workaround to not having an initStrong call.
2090 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2091 auto *ty = cast<llvm::PointerType>(srcValue->getType());
2092 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
2093 Builder.CreateStore(null, dstField);
2094 EmitARCStoreStrongCall(dstField, srcValue, true);
2096 // With optimization enabled, take advantage of the fact that
2097 // the blocks runtime guarantees a memcpy of the block data, and
2098 // just emit a retain of the src field.
2100 EmitARCRetainNonBlock(srcValue);
2102 // Unless EH cleanup is required, we don't need this anymore, so kill
2103 // it. It's not quite worth the annoyance to avoid creating it in the
2105 if (!needsEHCleanup(captureType.isDestructedType()))
2106 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
2110 case BlockCaptureEntityKind::BlockObject: {
2111 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
2112 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
2113 llvm::Value *dstAddr =
2114 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
2115 llvm::Value *args[] = {
2116 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2119 if (CI.isByRef() && C.getBlockVarCopyInit(CI.getVariable()).canThrow())
2120 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
2122 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
2125 case BlockCaptureEntityKind::None:
2129 // Ensure that we destroy the copied object if an exception is thrown later
2130 // in the helper function.
2131 pushCaptureCleanup(CopiedCapture.CopyKind, dstField, captureType, flags,
2132 /*ForCopyHelper*/ true, CI.getVariable(), *this);
2137 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2140 static BlockFieldFlags
2141 getBlockFieldFlagsForObjCObjectPointer(const BlockDecl::Capture &CI,
2143 BlockFieldFlags Flags = BLOCK_FIELD_IS_OBJECT;
2144 if (T->isBlockPointerType())
2145 Flags = BLOCK_FIELD_IS_BLOCK;
2149 static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
2150 computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
2151 const LangOptions &LangOpts) {
2152 if (CI.isEscapingByref()) {
2153 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2154 if (T.isObjCGCWeak())
2155 Flags |= BLOCK_FIELD_IS_WEAK;
2156 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
2159 switch (T.isDestructedType()) {
2160 case QualType::DK_cxx_destructor:
2161 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
2162 case QualType::DK_objc_strong_lifetime:
2163 // Use objc_storeStrong for __strong direct captures; the
2164 // dynamic tools really like it when we do this.
2165 return std::make_pair(BlockCaptureEntityKind::ARCStrong,
2166 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2167 case QualType::DK_objc_weak_lifetime:
2168 // Support __weak direct captures.
2169 return std::make_pair(BlockCaptureEntityKind::ARCWeak,
2170 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2171 case QualType::DK_nontrivial_c_struct:
2172 return std::make_pair(BlockCaptureEntityKind::NonTrivialCStruct,
2174 case QualType::DK_none: {
2175 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
2176 if (T->isObjCRetainableType() && !T.getQualifiers().hasObjCLifetime() &&
2177 !LangOpts.ObjCAutoRefCount)
2178 return std::make_pair(BlockCaptureEntityKind::BlockObject,
2179 getBlockFieldFlagsForObjCObjectPointer(CI, T));
2180 // Otherwise, we have nothing to do.
2181 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
2184 llvm_unreachable("after exhaustive DestructionKind switch");
2187 /// Generate the destroy-helper function for a block closure object:
2188 /// static void block_destroy_helper(block_t *theBlock);
2190 /// Note that this destroys a heap-allocated block closure object;
2191 /// it should not be confused with a 'byref destroy helper', which
2192 /// destroys the heap-allocated contents of an individual __block
2195 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
2196 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
2197 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures);
2198 std::string FuncName =
2199 getCopyDestroyHelperFuncName(DestroyedCaptures, blockInfo.BlockAlign,
2200 CaptureStrKind::DisposeHelper, CGM);
2202 if (llvm::GlobalValue *Func = CGM.getModule().getNamedValue(FuncName))
2203 return llvm::ConstantExpr::getBitCast(Func, VoidPtrTy);
2205 ASTContext &C = getContext();
2207 QualType ReturnTy = C.VoidTy;
2209 FunctionArgList args;
2210 ImplicitParamDecl SrcDecl(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2211 args.push_back(&SrcDecl);
2213 const CGFunctionInfo &FI =
2214 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2216 // FIXME: We'd like to put these into a mergable by content, with
2217 // internal linkage.
2218 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2220 llvm::Function *Fn =
2221 llvm::Function::Create(LTy, llvm::GlobalValue::LinkOnceODRLinkage,
2222 FuncName, &CGM.getModule());
2224 IdentifierInfo *II = &C.Idents.get(FuncName);
2226 SmallVector<QualType, 1> ArgTys;
2227 ArgTys.push_back(C.VoidPtrTy);
2228 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
2230 FunctionDecl *FD = FunctionDecl::Create(
2231 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
2232 FunctionTy, nullptr, SC_Static, false, false);
2234 setBlockHelperAttributesVisibility(blockInfo.CapturesNonExternalType, Fn, FI,
2236 StartFunction(FD, ReturnTy, Fn, FI, args);
2237 markAsIgnoreThreadCheckingAtRuntime(Fn);
2239 ApplyDebugLocation NL{*this, blockInfo.getBlockExpr()->getBeginLoc()};
2241 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
2243 Address src = GetAddrOfLocalVar(&SrcDecl);
2244 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
2245 src = Builder.CreateBitCast(src, structPtrTy, "block");
2247 CodeGenFunction::RunCleanupsScope cleanups(*this);
2249 for (const auto &DestroyedCapture : DestroyedCaptures) {
2250 const BlockDecl::Capture &CI = *DestroyedCapture.CI;
2251 const CGBlockInfo::Capture &capture = *DestroyedCapture.Capture;
2252 BlockFieldFlags flags = DestroyedCapture.DisposeFlags;
2255 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
2257 pushCaptureCleanup(DestroyedCapture.DisposeKind, srcField,
2258 CI.getVariable()->getType(), flags,
2259 /*ForCopyHelper*/ false, CI.getVariable(), *this);
2262 cleanups.ForceCleanup();
2266 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2271 /// Emits the copy/dispose helper functions for a __block object of id type.
2272 class ObjectByrefHelpers final : public BlockByrefHelpers {
2273 BlockFieldFlags Flags;
2276 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
2277 : BlockByrefHelpers(alignment), Flags(flags) {}
2279 void emitCopy(CodeGenFunction &CGF, Address destField,
2280 Address srcField) override {
2281 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
2283 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
2284 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
2286 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
2288 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
2289 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
2291 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
2292 CGF.EmitNounwindRuntimeCall(fn, args);
2295 void emitDispose(CodeGenFunction &CGF, Address field) override {
2296 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
2297 llvm::Value *value = CGF.Builder.CreateLoad(field);
2299 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER, false);
2302 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2303 id.AddInteger(Flags.getBitMask());
2307 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
2308 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
2310 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2312 void emitCopy(CodeGenFunction &CGF, Address destField,
2313 Address srcField) override {
2314 CGF.EmitARCMoveWeak(destField, srcField);
2317 void emitDispose(CodeGenFunction &CGF, Address field) override {
2318 CGF.EmitARCDestroyWeak(field);
2321 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2322 // 0 is distinguishable from all pointers and byref flags
2327 /// Emits the copy/dispose helpers for an ARC __block __strong variable
2328 /// that's not of block-pointer type.
2329 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
2331 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
2333 void emitCopy(CodeGenFunction &CGF, Address destField,
2334 Address srcField) override {
2335 // Do a "move" by copying the value and then zeroing out the old
2338 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
2341 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
2343 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
2344 CGF.Builder.CreateStore(null, destField);
2345 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
2346 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
2349 CGF.Builder.CreateStore(value, destField);
2350 CGF.Builder.CreateStore(null, srcField);
2353 void emitDispose(CodeGenFunction &CGF, Address field) override {
2354 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2357 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2358 // 1 is distinguishable from all pointers and byref flags
2363 /// Emits the copy/dispose helpers for an ARC __block __strong
2364 /// variable that's of block-pointer type.
2365 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
2367 ARCStrongBlockByrefHelpers(CharUnits alignment)
2368 : BlockByrefHelpers(alignment) {}
2370 void emitCopy(CodeGenFunction &CGF, Address destField,
2371 Address srcField) override {
2372 // Do the copy with objc_retainBlock; that's all that
2373 // _Block_object_assign would do anyway, and we'd have to pass the
2374 // right arguments to make sure it doesn't get no-op'ed.
2375 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
2376 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
2377 CGF.Builder.CreateStore(copy, destField);
2380 void emitDispose(CodeGenFunction &CGF, Address field) override {
2381 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
2384 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2385 // 2 is distinguishable from all pointers and byref flags
2390 /// Emits the copy/dispose helpers for a __block variable with a
2391 /// nontrivial copy constructor or destructor.
2392 class CXXByrefHelpers final : public BlockByrefHelpers {
2394 const Expr *CopyExpr;
2397 CXXByrefHelpers(CharUnits alignment, QualType type,
2398 const Expr *copyExpr)
2399 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
2401 bool needsCopy() const override { return CopyExpr != nullptr; }
2402 void emitCopy(CodeGenFunction &CGF, Address destField,
2403 Address srcField) override {
2404 if (!CopyExpr) return;
2405 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
2408 void emitDispose(CodeGenFunction &CGF, Address field) override {
2409 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2410 CGF.PushDestructorCleanup(VarType, field);
2411 CGF.PopCleanupBlocks(cleanupDepth);
2414 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2415 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2419 /// Emits the copy/dispose helpers for a __block variable that is a non-trivial
2421 class NonTrivialCStructByrefHelpers final : public BlockByrefHelpers {
2425 NonTrivialCStructByrefHelpers(CharUnits alignment, QualType type)
2426 : BlockByrefHelpers(alignment), VarType(type) {}
2428 void emitCopy(CodeGenFunction &CGF, Address destField,
2429 Address srcField) override {
2430 CGF.callCStructMoveConstructor(CGF.MakeAddrLValue(destField, VarType),
2431 CGF.MakeAddrLValue(srcField, VarType));
2434 bool needsDispose() const override {
2435 return VarType.isDestructedType();
2438 void emitDispose(CodeGenFunction &CGF, Address field) override {
2439 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
2440 CGF.pushDestroy(VarType.isDestructedType(), field, VarType);
2441 CGF.PopCleanupBlocks(cleanupDepth);
2444 void profileImpl(llvm::FoldingSetNodeID &id) const override {
2445 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
2448 } // end anonymous namespace
2450 static llvm::Constant *
2451 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
2452 BlockByrefHelpers &generator) {
2453 ASTContext &Context = CGF.getContext();
2455 QualType ReturnTy = Context.VoidTy;
2457 FunctionArgList args;
2458 ImplicitParamDecl Dst(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2459 args.push_back(&Dst);
2461 ImplicitParamDecl Src(Context, Context.VoidPtrTy, ImplicitParamDecl::Other);
2462 args.push_back(&Src);
2464 const CGFunctionInfo &FI =
2465 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
2467 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2469 // FIXME: We'd like to put these into a mergable by content, with
2470 // internal linkage.
2471 llvm::Function *Fn =
2472 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2473 "__Block_byref_object_copy_", &CGF.CGM.getModule());
2476 = &Context.Idents.get("__Block_byref_object_copy_");
2478 SmallVector<QualType, 2> ArgTys;
2479 ArgTys.push_back(Context.VoidPtrTy);
2480 ArgTys.push_back(Context.VoidPtrTy);
2481 QualType FunctionTy = Context.getFunctionType(ReturnTy, ArgTys, {});
2483 FunctionDecl *FD = FunctionDecl::Create(
2484 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2485 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2487 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2489 CGF.StartFunction(FD, ReturnTy, Fn, FI, args);
2491 if (generator.needsCopy()) {
2492 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
2495 Address destField = CGF.GetAddrOfLocalVar(&Dst);
2496 destField = Address(CGF.Builder.CreateLoad(destField),
2497 byrefInfo.ByrefAlignment);
2498 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
2499 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
2503 Address srcField = CGF.GetAddrOfLocalVar(&Src);
2504 srcField = Address(CGF.Builder.CreateLoad(srcField),
2505 byrefInfo.ByrefAlignment);
2506 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
2507 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
2510 generator.emitCopy(CGF, destField, srcField);
2513 CGF.FinishFunction();
2515 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2518 /// Build the copy helper for a __block variable.
2519 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
2520 const BlockByrefInfo &byrefInfo,
2521 BlockByrefHelpers &generator) {
2522 CodeGenFunction CGF(CGM);
2523 return generateByrefCopyHelper(CGF, byrefInfo, generator);
2526 /// Generate code for a __block variable's dispose helper.
2527 static llvm::Constant *
2528 generateByrefDisposeHelper(CodeGenFunction &CGF,
2529 const BlockByrefInfo &byrefInfo,
2530 BlockByrefHelpers &generator) {
2531 ASTContext &Context = CGF.getContext();
2532 QualType R = Context.VoidTy;
2534 FunctionArgList args;
2535 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2536 ImplicitParamDecl::Other);
2537 args.push_back(&Src);
2539 const CGFunctionInfo &FI =
2540 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
2542 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
2544 // FIXME: We'd like to put these into a mergable by content, with
2545 // internal linkage.
2546 llvm::Function *Fn =
2547 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2548 "__Block_byref_object_dispose_",
2549 &CGF.CGM.getModule());
2552 = &Context.Idents.get("__Block_byref_object_dispose_");
2554 SmallVector<QualType, 1> ArgTys;
2555 ArgTys.push_back(Context.VoidPtrTy);
2556 QualType FunctionTy = Context.getFunctionType(R, ArgTys, {});
2558 FunctionDecl *FD = FunctionDecl::Create(
2559 Context, Context.getTranslationUnitDecl(), SourceLocation(),
2560 SourceLocation(), II, FunctionTy, nullptr, SC_Static, false, false);
2562 CGF.CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
2564 CGF.StartFunction(FD, R, Fn, FI, args);
2566 if (generator.needsDispose()) {
2567 Address addr = CGF.GetAddrOfLocalVar(&Src);
2568 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2569 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2570 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2571 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
2573 generator.emitDispose(CGF, addr);
2576 CGF.FinishFunction();
2578 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
2581 /// Build the dispose helper for a __block variable.
2582 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
2583 const BlockByrefInfo &byrefInfo,
2584 BlockByrefHelpers &generator) {
2585 CodeGenFunction CGF(CGM);
2586 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
2589 /// Lazily build the copy and dispose helpers for a __block variable
2590 /// with the given information.
2592 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2594 llvm::FoldingSetNodeID id;
2595 generator.Profile(id);
2598 BlockByrefHelpers *node
2599 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2600 if (node) return static_cast<T*>(node);
2602 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2603 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
2605 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
2606 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2610 /// Build the copy and dispose helpers for the given __block variable
2611 /// emission. Places the helpers in the global cache. Returns null
2612 /// if no helpers are required.
2614 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
2615 const AutoVarEmission &emission) {
2616 const VarDecl &var = *emission.Variable;
2617 assert(var.isEscapingByref() &&
2618 "only escaping __block variables need byref helpers");
2620 QualType type = var.getType();
2622 auto &byrefInfo = getBlockByrefInfo(&var);
2624 // The alignment we care about for the purposes of uniquing byref
2625 // helpers is the alignment of the actual byref value field.
2626 CharUnits valueAlignment =
2627 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
2629 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2630 const Expr *copyExpr =
2631 CGM.getContext().getBlockVarCopyInit(&var).getCopyExpr();
2632 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
2634 return ::buildByrefHelpers(
2635 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
2638 // If type is a non-trivial C struct type that is non-trivial to
2639 // destructly move or destroy, build the copy and dispose helpers.
2640 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct ||
2641 type.isDestructedType() == QualType::DK_nontrivial_c_struct)
2642 return ::buildByrefHelpers(
2643 CGM, byrefInfo, NonTrivialCStructByrefHelpers(valueAlignment, type));
2645 // Otherwise, if we don't have a retainable type, there's nothing to do.
2646 // that the runtime does extra copies.
2647 if (!type->isObjCRetainableType()) return nullptr;
2649 Qualifiers qs = type.getQualifiers();
2651 // If we have lifetime, that dominates.
2652 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
2654 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2656 // These are just bits as far as the runtime is concerned.
2657 case Qualifiers::OCL_ExplicitNone:
2658 case Qualifiers::OCL_Autoreleasing:
2661 // Tell the runtime that this is ARC __weak, called by the
2663 case Qualifiers::OCL_Weak:
2664 return ::buildByrefHelpers(CGM, byrefInfo,
2665 ARCWeakByrefHelpers(valueAlignment));
2667 // ARC __strong __block variables need to be retained.
2668 case Qualifiers::OCL_Strong:
2669 // Block pointers need to be copied, and there's no direct
2670 // transfer possible.
2671 if (type->isBlockPointerType()) {
2672 return ::buildByrefHelpers(CGM, byrefInfo,
2673 ARCStrongBlockByrefHelpers(valueAlignment));
2675 // Otherwise, we transfer ownership of the retain from the stack
2678 return ::buildByrefHelpers(CGM, byrefInfo,
2679 ARCStrongByrefHelpers(valueAlignment));
2682 llvm_unreachable("fell out of lifetime switch!");
2685 BlockFieldFlags flags;
2686 if (type->isBlockPointerType()) {
2687 flags |= BLOCK_FIELD_IS_BLOCK;
2688 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2689 type->isObjCObjectPointerType()) {
2690 flags |= BLOCK_FIELD_IS_OBJECT;
2695 if (type.isObjCGCWeak())
2696 flags |= BLOCK_FIELD_IS_WEAK;
2698 return ::buildByrefHelpers(CGM, byrefInfo,
2699 ObjectByrefHelpers(valueAlignment, flags));
2702 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2704 bool followForward) {
2705 auto &info = getBlockByrefInfo(var);
2706 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2709 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2710 const BlockByrefInfo &info,
2712 const llvm::Twine &name) {
2713 // Chase the forwarding address if requested.
2714 if (followForward) {
2715 Address forwardingAddr =
2716 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2717 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2720 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2721 info.FieldOffset, name);
2724 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2729 /// void *__forwarding;
2730 /// int32_t __flags;
2732 /// void *__copy_helper; // only if needed
2733 /// void *__destroy_helper; // only if needed
2734 /// void *__byref_variable_layout;// only if needed
2735 /// char padding[X]; // only if needed
2739 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2740 auto it = BlockByrefInfos.find(D);
2741 if (it != BlockByrefInfos.end())
2744 llvm::StructType *byrefType =
2745 llvm::StructType::create(getLLVMContext(),
2746 "struct.__block_byref_" + D->getNameAsString());
2748 QualType Ty = D->getType();
2751 SmallVector<llvm::Type *, 8> types;
2754 types.push_back(Int8PtrTy);
2755 size += getPointerSize();
2757 // void *__forwarding;
2758 types.push_back(llvm::PointerType::getUnqual(byrefType));
2759 size += getPointerSize();
2762 types.push_back(Int32Ty);
2763 size += CharUnits::fromQuantity(4);
2766 types.push_back(Int32Ty);
2767 size += CharUnits::fromQuantity(4);
2769 // Note that this must match *exactly* the logic in buildByrefHelpers.
2770 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2771 if (hasCopyAndDispose) {
2772 /// void *__copy_helper;
2773 types.push_back(Int8PtrTy);
2774 size += getPointerSize();
2776 /// void *__destroy_helper;
2777 types.push_back(Int8PtrTy);
2778 size += getPointerSize();
2781 bool HasByrefExtendedLayout = false;
2782 Qualifiers::ObjCLifetime Lifetime;
2783 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2784 HasByrefExtendedLayout) {
2785 /// void *__byref_variable_layout;
2786 types.push_back(Int8PtrTy);
2787 size += CharUnits::fromQuantity(PointerSizeInBytes);
2791 llvm::Type *varTy = ConvertTypeForMem(Ty);
2793 bool packed = false;
2794 CharUnits varAlign = getContext().getDeclAlign(D);
2795 CharUnits varOffset = size.alignTo(varAlign);
2797 // We may have to insert padding.
2798 if (varOffset != size) {
2799 llvm::Type *paddingTy =
2800 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2802 types.push_back(paddingTy);
2805 // Conversely, we might have to prevent LLVM from inserting padding.
2806 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2807 > varAlign.getQuantity()) {
2810 types.push_back(varTy);
2812 byrefType->setBody(types, packed);
2814 BlockByrefInfo info;
2815 info.Type = byrefType;
2816 info.FieldIndex = types.size() - 1;
2817 info.FieldOffset = varOffset;
2818 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2820 auto pair = BlockByrefInfos.insert({D, info});
2821 assert(pair.second && "info was inserted recursively?");
2822 return pair.first->second;
2825 /// Initialize the structural components of a __block variable, i.e.
2826 /// everything but the actual object.
2827 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2828 // Find the address of the local.
2829 Address addr = emission.Addr;
2831 // That's an alloca of the byref structure type.
2832 llvm::StructType *byrefType = cast<llvm::StructType>(
2833 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2835 unsigned nextHeaderIndex = 0;
2836 CharUnits nextHeaderOffset;
2837 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2838 const Twine &name) {
2839 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2840 nextHeaderOffset, name);
2841 Builder.CreateStore(value, fieldAddr);
2844 nextHeaderOffset += fieldSize;
2847 // Build the byref helpers if necessary. This is null if we don't need any.
2848 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2850 const VarDecl &D = *emission.Variable;
2851 QualType type = D.getType();
2853 bool HasByrefExtendedLayout;
2854 Qualifiers::ObjCLifetime ByrefLifetime;
2855 bool ByRefHasLifetime =
2856 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2860 // Initialize the 'isa', which is just 0 or 1.
2862 if (type.isObjCGCWeak())
2864 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2865 storeHeaderField(V, getPointerSize(), "byref.isa");
2867 // Store the address of the variable into its own forwarding pointer.
2868 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2871 // c) the flags field is set to either 0 if no helper functions are
2872 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2874 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2875 if (ByRefHasLifetime) {
2876 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2877 else switch (ByrefLifetime) {
2878 case Qualifiers::OCL_Strong:
2879 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2881 case Qualifiers::OCL_Weak:
2882 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2884 case Qualifiers::OCL_ExplicitNone:
2885 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2887 case Qualifiers::OCL_None:
2888 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2889 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2894 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2895 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2896 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2897 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2898 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2899 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2900 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2901 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2902 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2903 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2904 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2905 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2906 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2907 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2908 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2909 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2914 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2915 getIntSize(), "byref.flags");
2917 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2918 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2919 storeHeaderField(V, getIntSize(), "byref.size");
2922 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2923 "byref.copyHelper");
2924 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2925 "byref.disposeHelper");
2928 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2929 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2930 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2934 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags,
2936 llvm::Value *F = CGM.getBlockObjectDispose();
2937 llvm::Value *args[] = {
2938 Builder.CreateBitCast(V, Int8PtrTy),
2939 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2943 EmitRuntimeCallOrInvoke(F, args);
2945 EmitNounwindRuntimeCall(F, args);
2948 void CodeGenFunction::enterByrefCleanup(CleanupKind Kind, Address Addr,
2949 BlockFieldFlags Flags,
2950 bool LoadBlockVarAddr, bool CanThrow) {
2951 EHStack.pushCleanup<CallBlockRelease>(Kind, Addr, Flags, LoadBlockVarAddr,
2955 /// Adjust the declaration of something from the blocks API.
2956 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2957 llvm::Constant *C) {
2958 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2960 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2961 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2962 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2963 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2965 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2966 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2967 "expected Function or GlobalVariable");
2969 const NamedDecl *ND = nullptr;
2970 for (const auto &Result : DC->lookup(&II))
2971 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2972 (ND = dyn_cast<VarDecl>(Result)))
2975 // TODO: support static blocks runtime
2976 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2977 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2978 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2980 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2981 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2985 if (CGM.getLangOpts().BlocksRuntimeOptional && GV->isDeclaration() &&
2986 GV->hasExternalLinkage())
2987 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2989 CGM.setDSOLocal(GV);
2992 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2993 if (BlockObjectDispose)
2994 return BlockObjectDispose;
2996 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2997 llvm::FunctionType *fty
2998 = llvm::FunctionType::get(VoidTy, args, false);
2999 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
3000 configureBlocksRuntimeObject(*this, BlockObjectDispose);
3001 return BlockObjectDispose;
3004 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
3005 if (BlockObjectAssign)
3006 return BlockObjectAssign;
3008 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
3009 llvm::FunctionType *fty
3010 = llvm::FunctionType::get(VoidTy, args, false);
3011 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
3012 configureBlocksRuntimeObject(*this, BlockObjectAssign);
3013 return BlockObjectAssign;
3016 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
3017 if (NSConcreteGlobalBlock)
3018 return NSConcreteGlobalBlock;
3020 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
3021 Int8PtrTy->getPointerTo(),
3023 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
3024 return NSConcreteGlobalBlock;
3027 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
3028 if (NSConcreteStackBlock)
3029 return NSConcreteStackBlock;
3031 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
3032 Int8PtrTy->getPointerTo(),
3034 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
3035 return NSConcreteStackBlock;