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 //===----------------------------------------------------------------------===//
15 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Module.h"
27 using namespace clang;
28 using namespace CodeGen;
30 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
32 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
33 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
34 DominatingIP(nullptr) {
36 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
42 // Anchor the vtable to this translation unit.
43 BlockByrefHelpers::~BlockByrefHelpers() {}
45 /// Build the given block as a global block.
46 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
50 /// Build the helper function to copy a block.
51 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
56 /// Build the helper function to dispose of a block.
57 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
62 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
64 /// meta-data and contains stationary information about the block literal.
65 /// Its definition will have 4 (or optinally 6) words.
67 /// struct Block_descriptor {
68 /// unsigned long reserved;
69 /// unsigned long size; // size of Block_literal metadata in bytes.
70 /// void *copy_func_helper_decl; // optional copy helper.
71 /// void *destroy_func_decl; // optioanl destructor helper.
72 /// void *block_method_encoding_address; // @encode for block literal signature.
73 /// void *block_layout_info; // encoding of captured block variables.
76 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
80 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
81 llvm::Type *i8p = nullptr;
82 if (CGM.getLangOpts().OpenCL)
84 llvm::Type::getInt8PtrTy(
85 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
87 i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
89 SmallVector<llvm::Constant*, 6> elements;
92 elements.push_back(llvm::ConstantInt::get(ulong, 0));
95 // FIXME: What is the right way to say this doesn't fit? We should give
96 // a user diagnostic in that case. Better fix would be to change the
98 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
103 // copy_func_helper_decl
104 elements.push_back(buildCopyHelper(CGM, blockInfo));
107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
110 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111 std::string typeAtEncoding =
112 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113 elements.push_back(llvm::ConstantExpr::getBitCast(
114 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
117 if (C.getLangOpts().ObjC1) {
118 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
121 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
124 elements.push_back(llvm::Constant::getNullValue(i8p));
126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
131 llvm::GlobalVariable *global =
132 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
133 llvm::GlobalValue::InternalLinkage,
134 init, "__block_descriptor_tmp", nullptr,
135 llvm::GlobalValue::NotThreadLocal,
138 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
142 Purely notional variadic template describing the layout of a block.
144 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
145 struct Block_literal {
146 /// Initialized to one of:
147 /// extern void *_NSConcreteStackBlock[];
148 /// extern void *_NSConcreteGlobalBlock[];
150 /// In theory, we could start one off malloc'ed by setting
151 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
153 /// extern void *_NSConcreteMallocBlock[];
154 struct objc_class *isa;
156 /// These are the flags (with corresponding bit number) that the
157 /// compiler is actually supposed to know about.
158 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
159 /// descriptor provides copy and dispose helper functions
160 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
161 /// object with a nontrivial destructor or copy constructor
162 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
164 /// 29. BLOCK_USE_STRET - indicates that the block function
165 /// uses stret, which objc_msgSend needs to know about
166 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
167 /// @encoded signature string
168 /// And we're not supposed to manipulate these:
169 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
170 /// to malloc'ed memory
171 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
172 /// to GC-allocated memory
173 /// Additionally, the bottom 16 bits are a reference count which
174 /// should be zero on the stack.
177 /// Reserved; should be zero-initialized.
180 /// Function pointer generated from block literal.
181 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
183 /// Block description metadata generated from block literal.
184 struct Block_descriptor *block_descriptor;
186 /// Captured values follow.
187 _CapturesTypes captures...;
191 /// The number of fields in a block header.
192 const unsigned BlockHeaderSize = 5;
195 /// A chunk of data that we actually have to capture in the block.
196 struct BlockLayoutChunk {
199 Qualifiers::ObjCLifetime Lifetime;
200 const BlockDecl::Capture *Capture; // null for 'this'
203 BlockLayoutChunk(CharUnits align, CharUnits size,
204 Qualifiers::ObjCLifetime lifetime,
205 const BlockDecl::Capture *capture,
207 : Alignment(align), Size(size), Lifetime(lifetime),
208 Capture(capture), Type(type) {}
210 /// Tell the block info that this chunk has the given field index.
211 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
213 info.CXXThisIndex = index;
214 info.CXXThisOffset = offset;
216 info.Captures.insert({Capture->getVariable(),
217 CGBlockInfo::Capture::makeIndex(index, offset)});
222 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
223 /// all __weak together. Preserve descending alignment in all situations.
224 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
225 if (left.Alignment != right.Alignment)
226 return left.Alignment > right.Alignment;
228 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
229 if (chunk.Capture && chunk.Capture->isByRef())
231 if (chunk.Lifetime == Qualifiers::OCL_Strong)
233 if (chunk.Lifetime == Qualifiers::OCL_Weak)
238 return getPrefOrder(left) < getPrefOrder(right);
240 } // end anonymous namespace
242 /// Determines if the given type is safe for constant capture in C++.
243 static bool isSafeForCXXConstantCapture(QualType type) {
244 const RecordType *recordType =
245 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
247 // Only records can be unsafe.
248 if (!recordType) return true;
250 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
252 // Maintain semantics for classes with non-trivial dtors or copy ctors.
253 if (!record->hasTrivialDestructor()) return false;
254 if (record->hasNonTrivialCopyConstructor()) return false;
256 // Otherwise, we just have to make sure there aren't any mutable
257 // fields that might have changed since initialization.
258 return !record->hasMutableFields();
261 /// It is illegal to modify a const object after initialization.
262 /// Therefore, if a const object has a constant initializer, we don't
263 /// actually need to keep storage for it in the block; we'll just
264 /// rematerialize it at the start of the block function. This is
265 /// acceptable because we make no promises about address stability of
266 /// captured variables.
267 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
268 CodeGenFunction *CGF,
269 const VarDecl *var) {
270 // Return if this is a function paramter. We shouldn't try to
271 // rematerialize default arguments of function parameters.
272 if (isa<ParmVarDecl>(var))
275 QualType type = var->getType();
277 // We can only do this if the variable is const.
278 if (!type.isConstQualified()) return nullptr;
280 // Furthermore, in C++ we have to worry about mutable fields:
281 // C++ [dcl.type.cv]p4:
282 // Except that any class member declared mutable can be
283 // modified, any attempt to modify a const object during its
284 // lifetime results in undefined behavior.
285 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
288 // If the variable doesn't have any initializer (shouldn't this be
289 // invalid?), it's not clear what we should do. Maybe capture as
291 const Expr *init = var->getInit();
292 if (!init) return nullptr;
294 return CGM.EmitConstantInit(*var, CGF);
297 /// Get the low bit of a nonzero character count. This is the
298 /// alignment of the nth byte if the 0th byte is universally aligned.
299 static CharUnits getLowBit(CharUnits v) {
300 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
303 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
304 SmallVectorImpl<llvm::Type*> &elementTypes) {
305 // The header is basically 'struct { void *; int; int; void *; void *; }'.
306 // Assert that that struct is packed.
307 assert(CGM.getIntSize() <= CGM.getPointerSize());
308 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
309 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
311 info.BlockAlign = CGM.getPointerAlign();
312 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
314 assert(elementTypes.empty());
315 elementTypes.push_back(CGM.VoidPtrTy);
316 elementTypes.push_back(CGM.IntTy);
317 elementTypes.push_back(CGM.IntTy);
318 elementTypes.push_back(CGM.VoidPtrTy);
319 elementTypes.push_back(CGM.getBlockDescriptorType());
321 assert(elementTypes.size() == BlockHeaderSize);
324 /// Compute the layout of the given block. Attempts to lay the block
325 /// out with minimal space requirements.
326 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
328 ASTContext &C = CGM.getContext();
329 const BlockDecl *block = info.getBlockDecl();
331 SmallVector<llvm::Type*, 8> elementTypes;
332 initializeForBlockHeader(CGM, info, elementTypes);
334 if (!block->hasCaptures()) {
336 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
337 info.CanBeGlobal = true;
340 else if (C.getLangOpts().ObjC1 &&
341 CGM.getLangOpts().getGC() == LangOptions::NonGC)
342 info.HasCapturedVariableLayout = true;
344 // Collect the layout chunks.
345 SmallVector<BlockLayoutChunk, 16> layout;
346 layout.reserve(block->capturesCXXThis() +
347 (block->capture_end() - block->capture_begin()));
349 CharUnits maxFieldAlign;
352 if (block->capturesCXXThis()) {
353 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
354 "Can't capture 'this' outside a method");
355 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
357 // Theoretically, this could be in a different address space, so
358 // don't assume standard pointer size/align.
359 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
360 std::pair<CharUnits,CharUnits> tinfo
361 = CGM.getContext().getTypeInfoInChars(thisType);
362 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
364 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
365 Qualifiers::OCL_None,
369 // Next, all the block captures.
370 for (const auto &CI : block->captures()) {
371 const VarDecl *variable = CI.getVariable();
374 // We have to copy/dispose of the __block reference.
375 info.NeedsCopyDispose = true;
377 // Just use void* instead of a pointer to the byref type.
378 CharUnits align = CGM.getPointerAlign();
379 maxFieldAlign = std::max(maxFieldAlign, align);
381 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
382 Qualifiers::OCL_None, &CI,
387 // Otherwise, build a layout chunk with the size and alignment of
389 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
390 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
394 // If we have a lifetime qualifier, honor it for capture purposes.
395 // That includes *not* copying it if it's __unsafe_unretained.
396 Qualifiers::ObjCLifetime lifetime =
397 variable->getType().getObjCLifetime();
400 case Qualifiers::OCL_None: llvm_unreachable("impossible");
401 case Qualifiers::OCL_ExplicitNone:
402 case Qualifiers::OCL_Autoreleasing:
405 case Qualifiers::OCL_Strong:
406 case Qualifiers::OCL_Weak:
407 info.NeedsCopyDispose = true;
410 // Block pointers require copy/dispose. So do Objective-C pointers.
411 } else if (variable->getType()->isObjCRetainableType()) {
412 // But honor the inert __unsafe_unretained qualifier, which doesn't
413 // actually make it into the type system.
414 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
415 lifetime = Qualifiers::OCL_ExplicitNone;
417 info.NeedsCopyDispose = true;
418 // used for mrr below.
419 lifetime = Qualifiers::OCL_Strong;
422 // So do types that require non-trivial copy construction.
423 } else if (CI.hasCopyExpr()) {
424 info.NeedsCopyDispose = true;
425 info.HasCXXObject = true;
427 // And so do types with destructors.
428 } else if (CGM.getLangOpts().CPlusPlus) {
429 if (const CXXRecordDecl *record =
430 variable->getType()->getAsCXXRecordDecl()) {
431 if (!record->hasTrivialDestructor()) {
432 info.HasCXXObject = true;
433 info.NeedsCopyDispose = true;
438 QualType VT = variable->getType();
439 CharUnits size = C.getTypeSizeInChars(VT);
440 CharUnits align = C.getDeclAlign(variable);
442 maxFieldAlign = std::max(maxFieldAlign, align);
444 llvm::Type *llvmType =
445 CGM.getTypes().ConvertTypeForMem(VT);
447 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
450 // If that was everything, we're done here.
451 if (layout.empty()) {
453 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
454 info.CanBeGlobal = true;
458 // Sort the layout by alignment. We have to use a stable sort here
459 // to get reproducible results. There should probably be an
460 // llvm::array_pod_stable_sort.
461 std::stable_sort(layout.begin(), layout.end());
463 // Needed for blocks layout info.
464 info.BlockHeaderForcedGapOffset = info.BlockSize;
465 info.BlockHeaderForcedGapSize = CharUnits::Zero();
467 CharUnits &blockSize = info.BlockSize;
468 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
470 // Assuming that the first byte in the header is maximally aligned,
471 // get the alignment of the first byte following the header.
472 CharUnits endAlign = getLowBit(blockSize);
474 // If the end of the header isn't satisfactorily aligned for the
475 // maximum thing, look for things that are okay with the header-end
476 // alignment, and keep appending them until we get something that's
477 // aligned right. This algorithm is only guaranteed optimal if
478 // that condition is satisfied at some point; otherwise we can get
480 // header // next byte has alignment 4
481 // something_with_size_5; // next byte has alignment 1
482 // something_with_alignment_8;
483 // which has 7 bytes of padding, as opposed to the naive solution
484 // which might have less (?).
485 if (endAlign < maxFieldAlign) {
486 SmallVectorImpl<BlockLayoutChunk>::iterator
487 li = layout.begin() + 1, le = layout.end();
489 // Look for something that the header end is already
490 // satisfactorily aligned for.
491 for (; li != le && endAlign < li->Alignment; ++li)
494 // If we found something that's naturally aligned for the end of
495 // the header, keep adding things...
497 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
498 for (; li != le; ++li) {
499 assert(endAlign >= li->Alignment);
501 li->setIndex(info, elementTypes.size(), blockSize);
502 elementTypes.push_back(li->Type);
503 blockSize += li->Size;
504 endAlign = getLowBit(blockSize);
506 // ...until we get to the alignment of the maximum field.
507 if (endAlign >= maxFieldAlign) {
511 // Don't re-append everything we just appended.
512 layout.erase(first, li);
516 assert(endAlign == getLowBit(blockSize));
518 // At this point, we just have to add padding if the end align still
519 // isn't aligned right.
520 if (endAlign < maxFieldAlign) {
521 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
522 CharUnits padding = newBlockSize - blockSize;
524 // If we haven't yet added any fields, remember that there was an
525 // initial gap; this need to go into the block layout bit map.
526 if (blockSize == info.BlockHeaderForcedGapOffset) {
527 info.BlockHeaderForcedGapSize = padding;
530 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
531 padding.getQuantity()));
532 blockSize = newBlockSize;
533 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
536 assert(endAlign >= maxFieldAlign);
537 assert(endAlign == getLowBit(blockSize));
538 // Slam everything else on now. This works because they have
539 // strictly decreasing alignment and we expect that size is always a
540 // multiple of alignment.
541 for (SmallVectorImpl<BlockLayoutChunk>::iterator
542 li = layout.begin(), le = layout.end(); li != le; ++li) {
543 if (endAlign < li->Alignment) {
544 // size may not be multiple of alignment. This can only happen with
545 // an over-aligned variable. We will be adding a padding field to
546 // make the size be multiple of alignment.
547 CharUnits padding = li->Alignment - endAlign;
548 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
549 padding.getQuantity()));
550 blockSize += padding;
551 endAlign = getLowBit(blockSize);
553 assert(endAlign >= li->Alignment);
554 li->setIndex(info, elementTypes.size(), blockSize);
555 elementTypes.push_back(li->Type);
556 blockSize += li->Size;
557 endAlign = getLowBit(blockSize);
561 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
564 /// Enter the scope of a block. This should be run at the entrance to
565 /// a full-expression so that the block's cleanups are pushed at the
566 /// right place in the stack.
567 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
568 assert(CGF.HaveInsertPoint());
570 // Allocate the block info and place it at the head of the list.
571 CGBlockInfo &blockInfo =
572 *new CGBlockInfo(block, CGF.CurFn->getName());
573 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
574 CGF.FirstBlockInfo = &blockInfo;
576 // Compute information about the layout, etc., of this block,
577 // pushing cleanups as necessary.
578 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
580 // Nothing else to do if it can be global.
581 if (blockInfo.CanBeGlobal) return;
583 // Make the allocation for the block.
584 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
585 blockInfo.BlockAlign, "block");
587 // If there are cleanups to emit, enter them (but inactive).
588 if (!blockInfo.NeedsCopyDispose) return;
590 // Walk through the captures (in order) and find the ones not
591 // captured by constant.
592 for (const auto &CI : block->captures()) {
593 // Ignore __block captures; there's nothing special in the
594 // on-stack block that we need to do for them.
595 if (CI.isByRef()) continue;
597 // Ignore variables that are constant-captured.
598 const VarDecl *variable = CI.getVariable();
599 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
600 if (capture.isConstant()) continue;
602 // Ignore objects that aren't destructed.
603 QualType::DestructionKind dtorKind =
604 variable->getType().isDestructedType();
605 if (dtorKind == QualType::DK_none) continue;
607 CodeGenFunction::Destroyer *destroyer;
609 // Block captures count as local values and have imprecise semantics.
610 // They also can't be arrays, so need to worry about that.
611 if (dtorKind == QualType::DK_objc_strong_lifetime) {
612 destroyer = CodeGenFunction::destroyARCStrongImprecise;
614 destroyer = CGF.getDestroyer(dtorKind);
617 // GEP down to the address.
618 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
620 capture.getOffset());
622 // We can use that GEP as the dominating IP.
623 if (!blockInfo.DominatingIP)
624 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
626 CleanupKind cleanupKind = InactiveNormalCleanup;
627 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
628 if (useArrayEHCleanup)
629 cleanupKind = InactiveNormalAndEHCleanup;
631 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
632 destroyer, useArrayEHCleanup);
634 // Remember where that cleanup was.
635 capture.setCleanup(CGF.EHStack.stable_begin());
639 /// Enter a full-expression with a non-trivial number of objects to
640 /// clean up. This is in this file because, at the moment, the only
641 /// kind of cleanup object is a BlockDecl*.
642 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
643 assert(E->getNumObjects() != 0);
644 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
645 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
646 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
647 enterBlockScope(*this, *i);
651 /// Find the layout for the given block in a linked list and remove it.
652 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
653 const BlockDecl *block) {
655 assert(head && *head);
656 CGBlockInfo *cur = *head;
658 // If this is the block we're looking for, splice it out of the list.
659 if (cur->getBlockDecl() == block) {
660 *head = cur->NextBlockInfo;
664 head = &cur->NextBlockInfo;
668 /// Destroy a chain of block layouts.
669 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
670 assert(head && "destroying an empty chain");
672 CGBlockInfo *cur = head;
673 head = cur->NextBlockInfo;
675 } while (head != nullptr);
678 /// Emit a block literal expression in the current function.
679 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
680 // If the block has no captures, we won't have a pre-computed
682 if (!blockExpr->getBlockDecl()->hasCaptures()) {
683 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
684 computeBlockInfo(CGM, this, blockInfo);
685 blockInfo.BlockExpression = blockExpr;
686 return EmitBlockLiteral(blockInfo);
689 // Find the block info for this block and take ownership of it.
690 std::unique_ptr<CGBlockInfo> blockInfo;
691 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
692 blockExpr->getBlockDecl()));
694 blockInfo->BlockExpression = blockExpr;
695 return EmitBlockLiteral(*blockInfo);
698 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
699 // Using the computed layout, generate the actual block function.
700 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
701 llvm::Constant *blockFn
702 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
705 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
707 // If there is nothing to capture, we can emit this as a global block.
708 if (blockInfo.CanBeGlobal)
709 return buildGlobalBlock(CGM, blockInfo, blockFn);
711 // Otherwise, we have to emit this as a local block.
713 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
714 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
716 // Build the block descriptor.
717 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
719 Address blockAddr = blockInfo.LocalAddress;
720 assert(blockAddr.isValid() && "block has no address!");
722 // Compute the initial on-stack block flags.
723 BlockFlags flags = BLOCK_HAS_SIGNATURE;
724 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
725 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
726 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
727 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
730 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
731 return Builder.CreateStructGEP(blockAddr, index, offset, name);
734 [&](llvm::Value *value, unsigned index, CharUnits offset,
736 Builder.CreateStore(value, projectField(index, offset, name));
739 // Initialize the block header.
741 // We assume all the header fields are densely packed.
744 auto addHeaderField =
745 [&](llvm::Value *value, CharUnits size, const Twine &name) {
746 storeField(value, index, offset, name);
751 addHeaderField(isa, getPointerSize(), "block.isa");
752 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
753 getIntSize(), "block.flags");
754 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
755 getIntSize(), "block.reserved");
756 addHeaderField(blockFn, getPointerSize(), "block.invoke");
757 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
760 // Finally, capture all the values into the block.
761 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
764 if (blockDecl->capturesCXXThis()) {
765 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
766 "block.captured-this.addr");
767 Builder.CreateStore(LoadCXXThis(), addr);
770 // Next, captured variables.
771 for (const auto &CI : blockDecl->captures()) {
772 const VarDecl *variable = CI.getVariable();
773 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
775 // Ignore constant captures.
776 if (capture.isConstant()) continue;
778 QualType type = variable->getType();
780 // This will be a [[type]]*, except that a byref entry will just be
783 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
785 // Compute the address of the thing we're going to move into the
787 Address src = Address::invalid();
789 if (blockDecl->isConversionFromLambda()) {
790 // The lambda capture in a lambda's conversion-to-block-pointer is
791 // special; we'll simply emit it directly.
792 src = Address::invalid();
793 } else if (CI.isByRef()) {
794 if (BlockInfo && CI.isNested()) {
795 // We need to use the capture from the enclosing block.
796 const CGBlockInfo::Capture &enclosingCapture =
797 BlockInfo->getCapture(variable);
799 // This is a [[type]]*, except that a byref entry wil just be an i8**.
800 src = Builder.CreateStructGEP(LoadBlockStruct(),
801 enclosingCapture.getIndex(),
802 enclosingCapture.getOffset(),
803 "block.capture.addr");
805 auto I = LocalDeclMap.find(variable);
806 assert(I != LocalDeclMap.end());
810 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
811 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
812 type.getNonReferenceType(), VK_LValue,
814 src = EmitDeclRefLValue(&declRef).getAddress();
817 // For byrefs, we just write the pointer to the byref struct into
818 // the block field. There's no need to chase the forwarding
819 // pointer at this point, since we're building something that will
820 // live a shorter life than the stack byref anyway.
822 // Get a void* that points to the byref struct.
823 llvm::Value *byrefPointer;
825 byrefPointer = Builder.CreateLoad(src, "byref.capture");
827 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
829 // Write that void* into the capture field.
830 Builder.CreateStore(byrefPointer, blockField);
832 // If we have a copy constructor, evaluate that into the block field.
833 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
834 if (blockDecl->isConversionFromLambda()) {
835 // If we have a lambda conversion, emit the expression
836 // directly into the block instead.
838 AggValueSlot::forAddr(blockField, Qualifiers(),
839 AggValueSlot::IsDestructed,
840 AggValueSlot::DoesNotNeedGCBarriers,
841 AggValueSlot::IsNotAliased);
842 EmitAggExpr(copyExpr, Slot);
844 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
847 // If it's a reference variable, copy the reference into the block field.
848 } else if (type->isReferenceType()) {
849 Builder.CreateStore(src.getPointer(), blockField);
851 // If this is an ARC __strong block-pointer variable, don't do a
854 // TODO: this can be generalized into the normal initialization logic:
855 // we should never need to do a block-copy when initializing a local
856 // variable, because the local variable's lifetime should be strictly
857 // contained within the stack block's.
858 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
859 type->isBlockPointerType()) {
860 // Load the block and do a simple retain.
861 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
862 value = EmitARCRetainNonBlock(value);
864 // Do a primitive store to the block field.
865 Builder.CreateStore(value, blockField);
867 // Otherwise, fake up a POD copy into the block field.
869 // Fake up a new variable so that EmitScalarInit doesn't think
870 // we're referring to the variable in its own initializer.
871 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
872 SourceLocation(), /*name*/ nullptr,
875 // We use one of these or the other depending on whether the
876 // reference is nested.
877 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
878 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
879 type, VK_LValue, SourceLocation());
881 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
882 &declRef, VK_RValue);
883 // FIXME: Pass a specific location for the expr init so that the store is
884 // attributed to a reasonable location - otherwise it may be attributed to
885 // locations of subexpressions in the initialization.
886 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
887 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
888 /*captured by init*/ false);
891 // Activate the cleanup if layout pushed one.
893 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
894 if (cleanup.isValid())
895 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
899 // Cast to the converted block-pointer type, which happens (somewhat
900 // unfortunately) to be a pointer to function type.
901 llvm::Value *result =
902 Builder.CreateBitCast(blockAddr.getPointer(),
903 ConvertType(blockInfo.getBlockExpr()->getType()));
909 llvm::Type *CodeGenModule::getBlockDescriptorType() {
910 if (BlockDescriptorType)
911 return BlockDescriptorType;
913 llvm::Type *UnsignedLongTy =
914 getTypes().ConvertType(getContext().UnsignedLongTy);
916 // struct __block_descriptor {
917 // unsigned long reserved;
918 // unsigned long block_size;
920 // // later, the following will be added
923 // void (*copyHelper)();
924 // void (*copyHelper)();
925 // } helpers; // !!! optional
927 // const char *signature; // the block signature
928 // const char *layout; // reserved
930 BlockDescriptorType =
931 llvm::StructType::create("struct.__block_descriptor",
932 UnsignedLongTy, UnsignedLongTy, nullptr);
934 // Now form a pointer to that.
935 unsigned AddrSpace = 0;
936 if (getLangOpts().OpenCL)
937 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
938 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
939 return BlockDescriptorType;
942 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
943 if (GenericBlockLiteralType)
944 return GenericBlockLiteralType;
946 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
948 // struct __block_literal_generic {
952 // void (*__invoke)(void *);
953 // struct __block_descriptor *__descriptor;
955 GenericBlockLiteralType =
956 llvm::StructType::create("struct.__block_literal_generic",
957 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
958 BlockDescPtrTy, nullptr);
960 return GenericBlockLiteralType;
963 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
964 ReturnValueSlot ReturnValue) {
965 const BlockPointerType *BPT =
966 E->getCallee()->getType()->getAs<BlockPointerType>();
968 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
970 // Get a pointer to the generic block literal.
971 llvm::Type *BlockLiteralTy =
972 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
974 // Bitcast the callee to a block literal.
975 llvm::Value *BlockLiteral =
976 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
978 // Get the function pointer from the literal.
979 llvm::Value *FuncPtr =
980 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
982 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
984 // Add the block literal.
986 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
988 QualType FnType = BPT->getPointeeType();
990 // And the rest of the arguments.
991 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
993 // Load the function.
994 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
996 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
997 const CGFunctionInfo &FnInfo =
998 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
1000 // Cast the function pointer to the right type.
1001 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
1003 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
1004 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
1006 // And call the block.
1007 return EmitCall(FnInfo, Func, ReturnValue, Args);
1010 Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1012 assert(BlockInfo && "evaluating block ref without block information?");
1013 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1015 // Handle constant captures.
1016 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
1019 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1020 capture.getOffset(), "block.capture.addr");
1023 // addr should be a void** right now. Load, then cast the result
1026 auto &byrefInfo = getBlockByrefInfo(variable);
1027 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1029 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1030 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
1032 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1033 variable->getName());
1036 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1037 addr = EmitLoadOfReference(addr, refType);
1044 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1046 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1047 blockInfo.BlockExpression = blockExpr;
1049 // Compute information about the layout, etc., of this block.
1050 computeBlockInfo(*this, nullptr, blockInfo);
1052 // Using that metadata, generate the actual block function.
1053 llvm::Constant *blockFn;
1055 CodeGenFunction::DeclMapTy LocalDeclMap;
1056 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1061 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1063 return buildGlobalBlock(*this, blockInfo, blockFn);
1066 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1067 const CGBlockInfo &blockInfo,
1068 llvm::Constant *blockFn) {
1069 assert(blockInfo.CanBeGlobal);
1071 // Generate the constants for the block literal initializer.
1072 llvm::Constant *fields[BlockHeaderSize];
1075 fields[0] = CGM.getNSConcreteGlobalBlock();
1078 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1079 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1081 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1084 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1087 fields[3] = blockFn;
1090 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1092 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1094 llvm::GlobalVariable *literal =
1095 new llvm::GlobalVariable(CGM.getModule(),
1098 llvm::GlobalVariable::InternalLinkage,
1100 "__block_literal_global");
1101 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1103 // Return a constant of the appropriately-casted type.
1104 llvm::Type *requiredType =
1105 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1106 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1109 void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1112 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1114 llvm::Value *localAddr = nullptr;
1115 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1116 // Allocate a stack slot to let the debug info survive the RA.
1117 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1118 Builder.CreateStore(arg, alloc);
1119 localAddr = Builder.CreateLoad(alloc);
1122 if (CGDebugInfo *DI = getDebugInfo()) {
1123 if (CGM.getCodeGenOpts().getDebugInfo() >=
1124 codegenoptions::LimitedDebugInfo) {
1125 DI->setLocation(D->getLocation());
1126 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1127 localAddr, Builder);
1131 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1132 ApplyDebugLocation Scope(*this, StartLoc);
1134 // Instead of messing around with LocalDeclMap, just set the value
1135 // directly as BlockPointer.
1136 BlockPointer = Builder.CreateBitCast(arg,
1137 BlockInfo->StructureType->getPointerTo(),
1141 Address CodeGenFunction::LoadBlockStruct() {
1142 assert(BlockInfo && "not in a block invocation function!");
1143 assert(BlockPointer && "no block pointer set!");
1144 return Address(BlockPointer, BlockInfo->BlockAlign);
1148 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1149 const CGBlockInfo &blockInfo,
1150 const DeclMapTy &ldm,
1151 bool IsLambdaConversionToBlock) {
1152 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1156 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1158 BlockInfo = &blockInfo;
1160 // Arrange for local static and local extern declarations to appear
1161 // to be local to this function as well, in case they're directly
1162 // referenced in a block.
1163 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1164 const auto *var = dyn_cast<VarDecl>(i->first);
1165 if (var && !var->hasLocalStorage())
1166 setAddrOfLocalVar(var, i->second);
1169 // Begin building the function declaration.
1171 // Build the argument list.
1172 FunctionArgList args;
1174 // The first argument is the block pointer. Just take it as a void*
1175 // and cast it later.
1176 QualType selfTy = getContext().VoidPtrTy;
1177 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1179 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1180 SourceLocation(), II, selfTy);
1181 args.push_back(&selfDecl);
1183 // Now add the rest of the parameters.
1184 args.append(blockDecl->param_begin(), blockDecl->param_end());
1186 // Create the function declaration.
1187 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1188 const CGFunctionInfo &fnInfo =
1189 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
1190 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1191 blockInfo.UsesStret = true;
1193 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1195 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1196 llvm::Function *fn = llvm::Function::Create(
1197 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1198 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1200 // Begin generating the function.
1201 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1202 blockDecl->getLocation(),
1203 blockInfo.getBlockExpr()->getBody()->getLocStart());
1205 // Okay. Undo some of what StartFunction did.
1207 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1208 // won't delete the dbg.declare intrinsics for captured variables.
1209 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1210 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1211 // Allocate a stack slot for it, so we can point the debugger to it
1212 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1215 // Set the DebugLocation to empty, so the store is recognized as a
1216 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1217 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1218 Builder.CreateStore(BlockPointer, Alloca);
1219 BlockPointerDbgLoc = Alloca.getPointer();
1222 // If we have a C++ 'this' reference, go ahead and force it into
1224 if (blockDecl->capturesCXXThis()) {
1226 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1227 blockInfo.CXXThisOffset, "block.captured-this");
1228 CXXThisValue = Builder.CreateLoad(addr, "this");
1231 // Also force all the constant captures.
1232 for (const auto &CI : blockDecl->captures()) {
1233 const VarDecl *variable = CI.getVariable();
1234 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1235 if (!capture.isConstant()) continue;
1237 CharUnits align = getContext().getDeclAlign(variable);
1239 CreateMemTemp(variable->getType(), align, "block.captured-const");
1241 Builder.CreateStore(capture.getConstant(), alloca);
1243 setAddrOfLocalVar(variable, alloca);
1246 // Save a spot to insert the debug information for all the DeclRefExprs.
1247 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1248 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1251 if (IsLambdaConversionToBlock)
1252 EmitLambdaBlockInvokeBody();
1254 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
1255 incrementProfileCounter(blockDecl->getBody());
1256 EmitStmt(blockDecl->getBody());
1259 // Remember where we were...
1260 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1262 // Go back to the entry.
1264 Builder.SetInsertPoint(entry, entry_ptr);
1266 // Emit debug information for all the DeclRefExprs.
1267 // FIXME: also for 'this'
1268 if (CGDebugInfo *DI = getDebugInfo()) {
1269 for (const auto &CI : blockDecl->captures()) {
1270 const VarDecl *variable = CI.getVariable();
1271 DI->EmitLocation(Builder, variable->getLocation());
1273 if (CGM.getCodeGenOpts().getDebugInfo() >=
1274 codegenoptions::LimitedDebugInfo) {
1275 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1276 if (capture.isConstant()) {
1277 auto addr = LocalDeclMap.find(variable)->second;
1278 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
1283 DI->EmitDeclareOfBlockDeclRefVariable(
1284 variable, BlockPointerDbgLoc, Builder, blockInfo,
1285 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
1288 // Recover location if it was changed in the above loop.
1289 DI->EmitLocation(Builder,
1290 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1293 // And resume where we left off.
1294 if (resume == nullptr)
1295 Builder.ClearInsertionPoint();
1297 Builder.SetInsertPoint(resume);
1299 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1305 notes.push_back(HelperInfo());
1306 HelperInfo ¬e = notes.back();
1307 note.index = capture.getIndex();
1308 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1309 note.cxxbar_import = ci->getCopyExpr();
1311 if (ci->isByRef()) {
1312 note.flag = BLOCK_FIELD_IS_BYREF;
1313 if (type.isObjCGCWeak())
1314 note.flag |= BLOCK_FIELD_IS_WEAK;
1315 } else if (type->isBlockPointerType()) {
1316 note.flag = BLOCK_FIELD_IS_BLOCK;
1318 note.flag = BLOCK_FIELD_IS_OBJECT;
1322 /// Generate the copy-helper function for a block closure object:
1323 /// static void block_copy_helper(block_t *dst, block_t *src);
1324 /// The runtime will have previously initialized 'dst' by doing a
1325 /// bit-copy of 'src'.
1327 /// Note that this copies an entire block closure object to the heap;
1328 /// it should not be confused with a 'byref copy helper', which moves
1329 /// the contents of an individual __block variable to the heap.
1331 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1332 ASTContext &C = getContext();
1334 FunctionArgList args;
1335 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1337 args.push_back(&dstDecl);
1338 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1340 args.push_back(&srcDecl);
1342 const CGFunctionInfo &FI =
1343 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1345 // FIXME: it would be nice if these were mergeable with things with
1346 // identical semantics.
1347 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1349 llvm::Function *Fn =
1350 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1351 "__copy_helper_block_", &CGM.getModule());
1354 = &CGM.getContext().Idents.get("__copy_helper_block_");
1356 FunctionDecl *FD = FunctionDecl::Create(C,
1357 C.getTranslationUnitDecl(),
1359 SourceLocation(), II, C.VoidTy,
1364 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1366 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1367 StartFunction(FD, C.VoidTy, Fn, FI, args);
1368 // Create a scope with an artificial location for the body of this function.
1369 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1370 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1372 Address src = GetAddrOfLocalVar(&srcDecl);
1373 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1374 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1376 Address dst = GetAddrOfLocalVar(&dstDecl);
1377 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
1378 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1380 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1382 for (const auto &CI : blockDecl->captures()) {
1383 const VarDecl *variable = CI.getVariable();
1384 QualType type = variable->getType();
1386 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1387 if (capture.isConstant()) continue;
1389 const Expr *copyExpr = CI.getCopyExpr();
1390 BlockFieldFlags flags;
1392 bool useARCWeakCopy = false;
1393 bool useARCStrongCopy = false;
1396 assert(!CI.isByRef());
1397 // don't bother computing flags
1399 } else if (CI.isByRef()) {
1400 flags = BLOCK_FIELD_IS_BYREF;
1401 if (type.isObjCGCWeak())
1402 flags |= BLOCK_FIELD_IS_WEAK;
1404 } else if (type->isObjCRetainableType()) {
1405 flags = BLOCK_FIELD_IS_OBJECT;
1406 bool isBlockPointer = type->isBlockPointerType();
1408 flags = BLOCK_FIELD_IS_BLOCK;
1410 // Special rules for ARC captures:
1411 Qualifiers qs = type.getQualifiers();
1413 // We need to register __weak direct captures with the runtime.
1414 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1415 useARCWeakCopy = true;
1417 // We need to retain the copied value for __strong direct captures.
1418 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1419 // If it's a block pointer, we have to copy the block and
1420 // assign that to the destination pointer, so we might as
1421 // well use _Block_object_assign. Otherwise we can avoid that.
1422 if (!isBlockPointer)
1423 useARCStrongCopy = true;
1425 // Non-ARC captures of retainable pointers are strong and
1426 // therefore require a call to _Block_object_assign.
1427 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1430 // Otherwise the memcpy is fine.
1435 // For all other types, the memcpy is fine.
1440 unsigned index = capture.getIndex();
1441 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1442 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
1444 // If there's an explicit copy expression, we do that.
1446 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1447 } else if (useARCWeakCopy) {
1448 EmitARCCopyWeak(dstField, srcField);
1450 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1451 if (useARCStrongCopy) {
1452 // At -O0, store null into the destination field (so that the
1453 // storeStrong doesn't over-release) and then call storeStrong.
1454 // This is a workaround to not having an initStrong call.
1455 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1456 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1457 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1458 Builder.CreateStore(null, dstField);
1459 EmitARCStoreStrongCall(dstField, srcValue, true);
1461 // With optimization enabled, take advantage of the fact that
1462 // the blocks runtime guarantees a memcpy of the block data, and
1463 // just emit a retain of the src field.
1465 EmitARCRetainNonBlock(srcValue);
1467 // We don't need this anymore, so kill it. It's not quite
1468 // worth the annoyance to avoid creating it in the first place.
1469 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
1472 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1473 llvm::Value *dstAddr =
1474 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
1475 llvm::Value *args[] = {
1476 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1479 bool copyCanThrow = false;
1480 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1481 const Expr *copyExpr =
1482 CGM.getContext().getBlockVarCopyInits(variable);
1484 copyCanThrow = true; // FIXME: reuse the noexcept logic
1489 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1491 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1499 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1502 /// Generate the destroy-helper function for a block closure object:
1503 /// static void block_destroy_helper(block_t *theBlock);
1505 /// Note that this destroys a heap-allocated block closure object;
1506 /// it should not be confused with a 'byref destroy helper', which
1507 /// destroys the heap-allocated contents of an individual __block
1510 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1511 ASTContext &C = getContext();
1513 FunctionArgList args;
1514 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1516 args.push_back(&srcDecl);
1518 const CGFunctionInfo &FI =
1519 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
1521 // FIXME: We'd like to put these into a mergable by content, with
1522 // internal linkage.
1523 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1525 llvm::Function *Fn =
1526 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1527 "__destroy_helper_block_", &CGM.getModule());
1530 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1532 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1534 SourceLocation(), II, C.VoidTy,
1538 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1540 // Create a scope with an artificial location for the body of this function.
1541 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1542 StartFunction(FD, C.VoidTy, Fn, FI, args);
1543 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1545 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1547 Address src = GetAddrOfLocalVar(&srcDecl);
1548 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
1549 src = Builder.CreateBitCast(src, structPtrTy, "block");
1551 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1553 CodeGenFunction::RunCleanupsScope cleanups(*this);
1555 for (const auto &CI : blockDecl->captures()) {
1556 const VarDecl *variable = CI.getVariable();
1557 QualType type = variable->getType();
1559 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1560 if (capture.isConstant()) continue;
1562 BlockFieldFlags flags;
1563 const CXXDestructorDecl *dtor = nullptr;
1565 bool useARCWeakDestroy = false;
1566 bool useARCStrongDestroy = false;
1569 flags = BLOCK_FIELD_IS_BYREF;
1570 if (type.isObjCGCWeak())
1571 flags |= BLOCK_FIELD_IS_WEAK;
1572 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1573 if (record->hasTrivialDestructor())
1575 dtor = record->getDestructor();
1576 } else if (type->isObjCRetainableType()) {
1577 flags = BLOCK_FIELD_IS_OBJECT;
1578 if (type->isBlockPointerType())
1579 flags = BLOCK_FIELD_IS_BLOCK;
1581 // Special rules for ARC captures.
1582 Qualifiers qs = type.getQualifiers();
1584 // Use objc_storeStrong for __strong direct captures; the
1585 // dynamic tools really like it when we do this.
1586 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1587 useARCStrongDestroy = true;
1589 // Support __weak direct captures.
1590 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1591 useARCWeakDestroy = true;
1593 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1594 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1597 // Otherwise, we have nothing to do.
1606 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
1608 // If there's an explicit copy expression, we do that.
1610 PushDestructorCleanup(dtor, srcField);
1612 // If this is a __weak capture, emit the release directly.
1613 } else if (useARCWeakDestroy) {
1614 EmitARCDestroyWeak(srcField);
1616 // Destroy strong objects with a call if requested.
1617 } else if (useARCStrongDestroy) {
1618 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1620 // Otherwise we call _Block_object_dispose. It wouldn't be too
1621 // hard to just emit this as a cleanup if we wanted to make sure
1622 // that things were done in reverse.
1624 llvm::Value *value = Builder.CreateLoad(srcField);
1625 value = Builder.CreateBitCast(value, VoidPtrTy);
1626 BuildBlockRelease(value, flags);
1630 cleanups.ForceCleanup();
1634 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1639 /// Emits the copy/dispose helper functions for a __block object of id type.
1640 class ObjectByrefHelpers final : public BlockByrefHelpers {
1641 BlockFieldFlags Flags;
1644 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1645 : BlockByrefHelpers(alignment), Flags(flags) {}
1647 void emitCopy(CodeGenFunction &CGF, Address destField,
1648 Address srcField) override {
1649 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1651 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1652 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1654 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1656 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1657 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1659 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
1660 CGF.EmitNounwindRuntimeCall(fn, args);
1663 void emitDispose(CodeGenFunction &CGF, Address field) override {
1664 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1665 llvm::Value *value = CGF.Builder.CreateLoad(field);
1667 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1670 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1671 id.AddInteger(Flags.getBitMask());
1675 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1676 class ARCWeakByrefHelpers final : public BlockByrefHelpers {
1678 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1680 void emitCopy(CodeGenFunction &CGF, Address destField,
1681 Address srcField) override {
1682 CGF.EmitARCMoveWeak(destField, srcField);
1685 void emitDispose(CodeGenFunction &CGF, Address field) override {
1686 CGF.EmitARCDestroyWeak(field);
1689 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1690 // 0 is distinguishable from all pointers and byref flags
1695 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1696 /// that's not of block-pointer type.
1697 class ARCStrongByrefHelpers final : public BlockByrefHelpers {
1699 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
1701 void emitCopy(CodeGenFunction &CGF, Address destField,
1702 Address srcField) override {
1703 // Do a "move" by copying the value and then zeroing out the old
1706 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1709 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1711 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1712 CGF.Builder.CreateStore(null, destField);
1713 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1714 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1717 CGF.Builder.CreateStore(value, destField);
1718 CGF.Builder.CreateStore(null, srcField);
1721 void emitDispose(CodeGenFunction &CGF, Address field) override {
1722 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1725 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1726 // 1 is distinguishable from all pointers and byref flags
1731 /// Emits the copy/dispose helpers for an ARC __block __strong
1732 /// variable that's of block-pointer type.
1733 class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
1735 ARCStrongBlockByrefHelpers(CharUnits alignment)
1736 : BlockByrefHelpers(alignment) {}
1738 void emitCopy(CodeGenFunction &CGF, Address destField,
1739 Address srcField) override {
1740 // Do the copy with objc_retainBlock; that's all that
1741 // _Block_object_assign would do anyway, and we'd have to pass the
1742 // right arguments to make sure it doesn't get no-op'ed.
1743 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
1744 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1745 CGF.Builder.CreateStore(copy, destField);
1748 void emitDispose(CodeGenFunction &CGF, Address field) override {
1749 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1752 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1753 // 2 is distinguishable from all pointers and byref flags
1758 /// Emits the copy/dispose helpers for a __block variable with a
1759 /// nontrivial copy constructor or destructor.
1760 class CXXByrefHelpers final : public BlockByrefHelpers {
1762 const Expr *CopyExpr;
1765 CXXByrefHelpers(CharUnits alignment, QualType type,
1766 const Expr *copyExpr)
1767 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1769 bool needsCopy() const override { return CopyExpr != nullptr; }
1770 void emitCopy(CodeGenFunction &CGF, Address destField,
1771 Address srcField) override {
1772 if (!CopyExpr) return;
1773 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1776 void emitDispose(CodeGenFunction &CGF, Address field) override {
1777 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1778 CGF.PushDestructorCleanup(VarType, field);
1779 CGF.PopCleanupBlocks(cleanupDepth);
1782 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1783 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1786 } // end anonymous namespace
1788 static llvm::Constant *
1789 generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1790 BlockByrefHelpers &generator) {
1791 ASTContext &Context = CGF.getContext();
1793 QualType R = Context.VoidTy;
1795 FunctionArgList args;
1796 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1798 args.push_back(&dst);
1800 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1802 args.push_back(&src);
1804 const CGFunctionInfo &FI =
1805 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1807 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1809 // FIXME: We'd like to put these into a mergable by content, with
1810 // internal linkage.
1811 llvm::Function *Fn =
1812 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1813 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1816 = &Context.Idents.get("__Block_byref_object_copy_");
1818 FunctionDecl *FD = FunctionDecl::Create(Context,
1819 Context.getTranslationUnitDecl(),
1821 SourceLocation(), II, R, nullptr,
1825 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1827 CGF.StartFunction(FD, R, Fn, FI, args);
1829 if (generator.needsCopy()) {
1830 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
1833 Address destField = CGF.GetAddrOfLocalVar(&dst);
1834 destField = Address(CGF.Builder.CreateLoad(destField),
1835 byrefInfo.ByrefAlignment);
1836 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1837 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1841 Address srcField = CGF.GetAddrOfLocalVar(&src);
1842 srcField = Address(CGF.Builder.CreateLoad(srcField),
1843 byrefInfo.ByrefAlignment);
1844 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1845 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1848 generator.emitCopy(CGF, destField, srcField);
1851 CGF.FinishFunction();
1853 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1856 /// Build the copy helper for a __block variable.
1857 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1858 const BlockByrefInfo &byrefInfo,
1859 BlockByrefHelpers &generator) {
1860 CodeGenFunction CGF(CGM);
1861 return generateByrefCopyHelper(CGF, byrefInfo, generator);
1864 /// Generate code for a __block variable's dispose helper.
1865 static llvm::Constant *
1866 generateByrefDisposeHelper(CodeGenFunction &CGF,
1867 const BlockByrefInfo &byrefInfo,
1868 BlockByrefHelpers &generator) {
1869 ASTContext &Context = CGF.getContext();
1870 QualType R = Context.VoidTy;
1872 FunctionArgList args;
1873 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1875 args.push_back(&src);
1877 const CGFunctionInfo &FI =
1878 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
1880 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
1882 // FIXME: We'd like to put these into a mergable by content, with
1883 // internal linkage.
1884 llvm::Function *Fn =
1885 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1886 "__Block_byref_object_dispose_",
1887 &CGF.CGM.getModule());
1890 = &Context.Idents.get("__Block_byref_object_dispose_");
1892 FunctionDecl *FD = FunctionDecl::Create(Context,
1893 Context.getTranslationUnitDecl(),
1895 SourceLocation(), II, R, nullptr,
1899 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1901 CGF.StartFunction(FD, R, Fn, FI, args);
1903 if (generator.needsDispose()) {
1904 Address addr = CGF.GetAddrOfLocalVar(&src);
1905 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1906 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1907 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1908 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
1910 generator.emitDispose(CGF, addr);
1913 CGF.FinishFunction();
1915 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1918 /// Build the dispose helper for a __block variable.
1919 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1920 const BlockByrefInfo &byrefInfo,
1921 BlockByrefHelpers &generator) {
1922 CodeGenFunction CGF(CGM);
1923 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
1926 /// Lazily build the copy and dispose helpers for a __block variable
1927 /// with the given information.
1929 static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1931 llvm::FoldingSetNodeID id;
1932 generator.Profile(id);
1935 BlockByrefHelpers *node
1936 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1937 if (node) return static_cast<T*>(node);
1939 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1940 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
1942 T *copy = new (CGM.getContext()) T(std::move(generator));
1943 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1947 /// Build the copy and dispose helpers for the given __block variable
1948 /// emission. Places the helpers in the global cache. Returns null
1949 /// if no helpers are required.
1951 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1952 const AutoVarEmission &emission) {
1953 const VarDecl &var = *emission.Variable;
1954 QualType type = var.getType();
1956 auto &byrefInfo = getBlockByrefInfo(&var);
1958 // The alignment we care about for the purposes of uniquing byref
1959 // helpers is the alignment of the actual byref value field.
1960 CharUnits valueAlignment =
1961 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
1963 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1964 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1965 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1967 return ::buildByrefHelpers(
1968 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
1971 // Otherwise, if we don't have a retainable type, there's nothing to do.
1972 // that the runtime does extra copies.
1973 if (!type->isObjCRetainableType()) return nullptr;
1975 Qualifiers qs = type.getQualifiers();
1977 // If we have lifetime, that dominates.
1978 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1980 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1982 // These are just bits as far as the runtime is concerned.
1983 case Qualifiers::OCL_ExplicitNone:
1984 case Qualifiers::OCL_Autoreleasing:
1987 // Tell the runtime that this is ARC __weak, called by the
1989 case Qualifiers::OCL_Weak:
1990 return ::buildByrefHelpers(CGM, byrefInfo,
1991 ARCWeakByrefHelpers(valueAlignment));
1993 // ARC __strong __block variables need to be retained.
1994 case Qualifiers::OCL_Strong:
1995 // Block pointers need to be copied, and there's no direct
1996 // transfer possible.
1997 if (type->isBlockPointerType()) {
1998 return ::buildByrefHelpers(CGM, byrefInfo,
1999 ARCStrongBlockByrefHelpers(valueAlignment));
2001 // Otherwise, we transfer ownership of the retain from the stack
2004 return ::buildByrefHelpers(CGM, byrefInfo,
2005 ARCStrongByrefHelpers(valueAlignment));
2008 llvm_unreachable("fell out of lifetime switch!");
2011 BlockFieldFlags flags;
2012 if (type->isBlockPointerType()) {
2013 flags |= BLOCK_FIELD_IS_BLOCK;
2014 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2015 type->isObjCObjectPointerType()) {
2016 flags |= BLOCK_FIELD_IS_OBJECT;
2021 if (type.isObjCGCWeak())
2022 flags |= BLOCK_FIELD_IS_WEAK;
2024 return ::buildByrefHelpers(CGM, byrefInfo,
2025 ObjectByrefHelpers(valueAlignment, flags));
2028 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2030 bool followForward) {
2031 auto &info = getBlockByrefInfo(var);
2032 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
2035 Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2036 const BlockByrefInfo &info,
2038 const llvm::Twine &name) {
2039 // Chase the forwarding address if requested.
2040 if (followForward) {
2041 Address forwardingAddr =
2042 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2043 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2046 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2047 info.FieldOffset, name);
2050 /// BuildByrefInfo - This routine changes a __block variable declared as T x
2055 /// void *__forwarding;
2056 /// int32_t __flags;
2058 /// void *__copy_helper; // only if needed
2059 /// void *__destroy_helper; // only if needed
2060 /// void *__byref_variable_layout;// only if needed
2061 /// char padding[X]; // only if needed
2065 const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2066 auto it = BlockByrefInfos.find(D);
2067 if (it != BlockByrefInfos.end())
2070 llvm::StructType *byrefType =
2071 llvm::StructType::create(getLLVMContext(),
2072 "struct.__block_byref_" + D->getNameAsString());
2074 QualType Ty = D->getType();
2077 SmallVector<llvm::Type *, 8> types;
2080 types.push_back(Int8PtrTy);
2081 size += getPointerSize();
2083 // void *__forwarding;
2084 types.push_back(llvm::PointerType::getUnqual(byrefType));
2085 size += getPointerSize();
2088 types.push_back(Int32Ty);
2089 size += CharUnits::fromQuantity(4);
2092 types.push_back(Int32Ty);
2093 size += CharUnits::fromQuantity(4);
2095 // Note that this must match *exactly* the logic in buildByrefHelpers.
2096 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2097 if (hasCopyAndDispose) {
2098 /// void *__copy_helper;
2099 types.push_back(Int8PtrTy);
2100 size += getPointerSize();
2102 /// void *__destroy_helper;
2103 types.push_back(Int8PtrTy);
2104 size += getPointerSize();
2107 bool HasByrefExtendedLayout = false;
2108 Qualifiers::ObjCLifetime Lifetime;
2109 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2110 HasByrefExtendedLayout) {
2111 /// void *__byref_variable_layout;
2112 types.push_back(Int8PtrTy);
2113 size += CharUnits::fromQuantity(PointerSizeInBytes);
2117 llvm::Type *varTy = ConvertTypeForMem(Ty);
2119 bool packed = false;
2120 CharUnits varAlign = getContext().getDeclAlign(D);
2121 CharUnits varOffset = size.alignTo(varAlign);
2123 // We may have to insert padding.
2124 if (varOffset != size) {
2125 llvm::Type *paddingTy =
2126 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2128 types.push_back(paddingTy);
2131 // Conversely, we might have to prevent LLVM from inserting padding.
2132 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2133 > varAlign.getQuantity()) {
2136 types.push_back(varTy);
2138 byrefType->setBody(types, packed);
2140 BlockByrefInfo info;
2141 info.Type = byrefType;
2142 info.FieldIndex = types.size() - 1;
2143 info.FieldOffset = varOffset;
2144 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2146 auto pair = BlockByrefInfos.insert({D, info});
2147 assert(pair.second && "info was inserted recursively?");
2148 return pair.first->second;
2151 /// Initialize the structural components of a __block variable, i.e.
2152 /// everything but the actual object.
2153 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2154 // Find the address of the local.
2155 Address addr = emission.Addr;
2157 // That's an alloca of the byref structure type.
2158 llvm::StructType *byrefType = cast<llvm::StructType>(
2159 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2161 unsigned nextHeaderIndex = 0;
2162 CharUnits nextHeaderOffset;
2163 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2164 const Twine &name) {
2165 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2166 nextHeaderOffset, name);
2167 Builder.CreateStore(value, fieldAddr);
2170 nextHeaderOffset += fieldSize;
2173 // Build the byref helpers if necessary. This is null if we don't need any.
2174 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
2176 const VarDecl &D = *emission.Variable;
2177 QualType type = D.getType();
2179 bool HasByrefExtendedLayout;
2180 Qualifiers::ObjCLifetime ByrefLifetime;
2181 bool ByRefHasLifetime =
2182 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2186 // Initialize the 'isa', which is just 0 or 1.
2188 if (type.isObjCGCWeak())
2190 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2191 storeHeaderField(V, getPointerSize(), "byref.isa");
2193 // Store the address of the variable into its own forwarding pointer.
2194 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
2197 // c) the flags field is set to either 0 if no helper functions are
2198 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2200 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2201 if (ByRefHasLifetime) {
2202 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2203 else switch (ByrefLifetime) {
2204 case Qualifiers::OCL_Strong:
2205 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2207 case Qualifiers::OCL_Weak:
2208 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2210 case Qualifiers::OCL_ExplicitNone:
2211 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2213 case Qualifiers::OCL_None:
2214 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2215 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2220 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2221 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2222 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2223 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2224 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2225 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2226 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2227 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2228 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2229 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2230 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2231 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2232 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2233 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2234 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2235 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2240 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2241 getIntSize(), "byref.flags");
2243 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2244 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2245 storeHeaderField(V, getIntSize(), "byref.size");
2248 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2249 "byref.copyHelper");
2250 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2251 "byref.disposeHelper");
2254 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2255 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2256 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
2260 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2261 llvm::Value *F = CGM.getBlockObjectDispose();
2262 llvm::Value *args[] = {
2263 Builder.CreateBitCast(V, Int8PtrTy),
2264 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2266 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2270 /// Release a __block variable.
2271 struct CallBlockRelease final : EHScopeStack::Cleanup {
2273 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2275 void Emit(CodeGenFunction &CGF, Flags flags) override {
2276 // Should we be passing FIELD_IS_WEAK here?
2277 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2280 } // end anonymous namespace
2282 /// Enter a cleanup to destroy a __block variable. Note that this
2283 /// cleanup should be a no-op if the variable hasn't left the stack
2284 /// yet; if a cleanup is required for the variable itself, that needs
2285 /// to be done externally.
2286 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2287 // We don't enter this cleanup if we're in pure-GC mode.
2288 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2291 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2292 emission.Addr.getPointer());
2295 /// Adjust the declaration of something from the blocks API.
2296 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2297 llvm::Constant *C) {
2298 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2300 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2301 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2302 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2303 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2305 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2306 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2307 "expected Function or GlobalVariable");
2309 const NamedDecl *ND = nullptr;
2310 for (const auto &Result : DC->lookup(&II))
2311 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2312 (ND = dyn_cast<VarDecl>(Result)))
2315 // TODO: support static blocks runtime
2316 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2317 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2318 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2320 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2321 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2325 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2328 if (GV->isDeclaration() && GV->hasExternalLinkage())
2329 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2332 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2333 if (BlockObjectDispose)
2334 return BlockObjectDispose;
2336 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2337 llvm::FunctionType *fty
2338 = llvm::FunctionType::get(VoidTy, args, false);
2339 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2340 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2341 return BlockObjectDispose;
2344 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2345 if (BlockObjectAssign)
2346 return BlockObjectAssign;
2348 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2349 llvm::FunctionType *fty
2350 = llvm::FunctionType::get(VoidTy, args, false);
2351 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2352 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2353 return BlockObjectAssign;
2356 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2357 if (NSConcreteGlobalBlock)
2358 return NSConcreteGlobalBlock;
2360 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2361 Int8PtrTy->getPointerTo(),
2363 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2364 return NSConcreteGlobalBlock;
2367 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2368 if (NSConcreteStackBlock)
2369 return NSConcreteStackBlock;
2371 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2372 Int8PtrTy->getPointerTo(),
2374 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2375 return NSConcreteStackBlock;