1 //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
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 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 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
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 = NULL;
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), 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 llvm::GlobalVariable *global =
129 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130 llvm::GlobalValue::InternalLinkage,
131 init, "__block_descriptor_tmp");
133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
137 Purely notional variadic template describing the layout of a block.
139 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140 struct Block_literal {
141 /// Initialized to one of:
142 /// extern void *_NSConcreteStackBlock[];
143 /// extern void *_NSConcreteGlobalBlock[];
145 /// In theory, we could start one off malloc'ed by setting
146 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
148 /// extern void *_NSConcreteMallocBlock[];
149 struct objc_class *isa;
151 /// These are the flags (with corresponding bit number) that the
152 /// compiler is actually supposed to know about.
153 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154 /// descriptor provides copy and dispose helper functions
155 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156 /// object with a nontrivial destructor or copy constructor
157 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
159 /// 29. BLOCK_USE_STRET - indicates that the block function
160 /// uses stret, which objc_msgSend needs to know about
161 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162 /// @encoded signature string
163 /// And we're not supposed to manipulate these:
164 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165 /// to malloc'ed memory
166 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167 /// to GC-allocated memory
168 /// Additionally, the bottom 16 bits are a reference count which
169 /// should be zero on the stack.
172 /// Reserved; should be zero-initialized.
175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
181 /// Captured values follow.
182 _CapturesTypes captures...;
186 /// The number of fields in a block header.
187 const unsigned BlockHeaderSize = 5;
190 /// A chunk of data that we actually have to capture in the block.
191 struct BlockLayoutChunk {
194 Qualifiers::ObjCLifetime Lifetime;
195 const BlockDecl::Capture *Capture; // null for 'this'
198 BlockLayoutChunk(CharUnits align, CharUnits size,
199 Qualifiers::ObjCLifetime lifetime,
200 const BlockDecl::Capture *capture,
202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
205 /// Tell the block info that this chunk has the given field index.
206 void setIndex(CGBlockInfo &info, unsigned index) {
208 info.CXXThisIndex = index;
210 info.Captures[Capture->getVariable()]
211 = CGBlockInfo::Capture::makeIndex(index);
215 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
216 /// all __weak together. Preserve descending alignment in all situations.
217 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
218 CharUnits LeftValue, RightValue;
219 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
220 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
222 if (left.Lifetime == Qualifiers::OCL_Strong &&
223 left.Alignment >= right.Alignment)
224 LeftValue = CharUnits::fromQuantity(64);
225 else if (LeftByref && left.Alignment >= right.Alignment)
226 LeftValue = CharUnits::fromQuantity(32);
227 else if (left.Lifetime == Qualifiers::OCL_Weak &&
228 left.Alignment >= right.Alignment)
229 LeftValue = CharUnits::fromQuantity(16);
231 LeftValue = left.Alignment;
232 if (right.Lifetime == Qualifiers::OCL_Strong &&
233 right.Alignment >= left.Alignment)
234 RightValue = CharUnits::fromQuantity(64);
235 else if (RightByref && right.Alignment >= left.Alignment)
236 RightValue = CharUnits::fromQuantity(32);
237 else if (right.Lifetime == Qualifiers::OCL_Weak &&
238 right.Alignment >= left.Alignment)
239 RightValue = CharUnits::fromQuantity(16);
241 RightValue = right.Alignment;
243 return LeftValue > RightValue;
247 /// Determines if the given type is safe for constant capture in C++.
248 static bool isSafeForCXXConstantCapture(QualType type) {
249 const RecordType *recordType =
250 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
252 // Only records can be unsafe.
253 if (!recordType) return true;
255 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
257 // Maintain semantics for classes with non-trivial dtors or copy ctors.
258 if (!record->hasTrivialDestructor()) return false;
259 if (record->hasNonTrivialCopyConstructor()) return false;
261 // Otherwise, we just have to make sure there aren't any mutable
262 // fields that might have changed since initialization.
263 return !record->hasMutableFields();
266 /// It is illegal to modify a const object after initialization.
267 /// Therefore, if a const object has a constant initializer, we don't
268 /// actually need to keep storage for it in the block; we'll just
269 /// rematerialize it at the start of the block function. This is
270 /// acceptable because we make no promises about address stability of
271 /// captured variables.
272 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
273 CodeGenFunction *CGF,
274 const VarDecl *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 ASTContext &C = CGM.getContext();
307 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
308 CharUnits ptrSize, ptrAlign, intSize, intAlign;
309 std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
310 std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
312 // Are there crazy embedded platforms where this isn't true?
313 assert(intSize <= ptrSize && "layout assumptions horribly violated");
315 CharUnits headerSize = ptrSize;
316 if (2 * intSize < ptrAlign) headerSize += ptrSize;
317 else headerSize += 2 * intSize;
318 headerSize += 2 * ptrSize;
320 info.BlockAlign = ptrAlign;
321 info.BlockSize = headerSize;
323 assert(elementTypes.empty());
324 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
325 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
326 elementTypes.push_back(i8p);
327 elementTypes.push_back(intTy);
328 elementTypes.push_back(intTy);
329 elementTypes.push_back(i8p);
330 elementTypes.push_back(CGM.getBlockDescriptorType());
332 assert(elementTypes.size() == BlockHeaderSize);
335 /// Compute the layout of the given block. Attempts to lay the block
336 /// out with minimal space requirements.
337 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
339 ASTContext &C = CGM.getContext();
340 const BlockDecl *block = info.getBlockDecl();
342 SmallVector<llvm::Type*, 8> elementTypes;
343 initializeForBlockHeader(CGM, info, elementTypes);
345 if (!block->hasCaptures()) {
347 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
348 info.CanBeGlobal = true;
351 else if (C.getLangOpts().ObjC1 &&
352 CGM.getLangOpts().getGC() == LangOptions::NonGC)
353 info.HasCapturedVariableLayout = true;
355 // Collect the layout chunks.
356 SmallVector<BlockLayoutChunk, 16> layout;
357 layout.reserve(block->capturesCXXThis() +
358 (block->capture_end() - block->capture_begin()));
360 CharUnits maxFieldAlign;
363 if (block->capturesCXXThis()) {
364 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
365 "Can't capture 'this' outside a method");
366 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
368 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
369 std::pair<CharUnits,CharUnits> tinfo
370 = CGM.getContext().getTypeInfoInChars(thisType);
371 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
373 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
374 Qualifiers::OCL_None,
378 // Next, all the block captures.
379 for (const auto &CI : block->captures()) {
380 const VarDecl *variable = CI.getVariable();
383 // We have to copy/dispose of the __block reference.
384 info.NeedsCopyDispose = true;
386 // Just use void* instead of a pointer to the byref type.
387 QualType byRefPtrTy = C.VoidPtrTy;
389 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
390 std::pair<CharUnits,CharUnits> tinfo
391 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
392 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
394 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
395 Qualifiers::OCL_None, &CI, llvmType));
399 // Otherwise, build a layout chunk with the size and alignment of
401 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
402 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
406 // If we have a lifetime qualifier, honor it for capture purposes.
407 // That includes *not* copying it if it's __unsafe_unretained.
408 Qualifiers::ObjCLifetime lifetime =
409 variable->getType().getObjCLifetime();
412 case Qualifiers::OCL_None: llvm_unreachable("impossible");
413 case Qualifiers::OCL_ExplicitNone:
414 case Qualifiers::OCL_Autoreleasing:
417 case Qualifiers::OCL_Strong:
418 case Qualifiers::OCL_Weak:
419 info.NeedsCopyDispose = true;
422 // Block pointers require copy/dispose. So do Objective-C pointers.
423 } else if (variable->getType()->isObjCRetainableType()) {
424 info.NeedsCopyDispose = true;
425 // used for mrr below.
426 lifetime = Qualifiers::OCL_Strong;
428 // So do types that require non-trivial copy construction.
429 } else if (CI.hasCopyExpr()) {
430 info.NeedsCopyDispose = true;
431 info.HasCXXObject = true;
433 // And so do types with destructors.
434 } else if (CGM.getLangOpts().CPlusPlus) {
435 if (const CXXRecordDecl *record =
436 variable->getType()->getAsCXXRecordDecl()) {
437 if (!record->hasTrivialDestructor()) {
438 info.HasCXXObject = true;
439 info.NeedsCopyDispose = true;
444 QualType VT = variable->getType();
445 CharUnits size = C.getTypeSizeInChars(VT);
446 CharUnits align = C.getDeclAlign(variable);
448 maxFieldAlign = std::max(maxFieldAlign, align);
450 llvm::Type *llvmType =
451 CGM.getTypes().ConvertTypeForMem(VT);
453 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
456 // If that was everything, we're done here.
457 if (layout.empty()) {
459 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460 info.CanBeGlobal = true;
464 // Sort the layout by alignment. We have to use a stable sort here
465 // to get reproducible results. There should probably be an
466 // llvm::array_pod_stable_sort.
467 std::stable_sort(layout.begin(), layout.end());
469 // Needed for blocks layout info.
470 info.BlockHeaderForcedGapOffset = info.BlockSize;
471 info.BlockHeaderForcedGapSize = CharUnits::Zero();
473 CharUnits &blockSize = info.BlockSize;
474 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
476 // Assuming that the first byte in the header is maximally aligned,
477 // get the alignment of the first byte following the header.
478 CharUnits endAlign = getLowBit(blockSize);
480 // If the end of the header isn't satisfactorily aligned for the
481 // maximum thing, look for things that are okay with the header-end
482 // alignment, and keep appending them until we get something that's
483 // aligned right. This algorithm is only guaranteed optimal if
484 // that condition is satisfied at some point; otherwise we can get
486 // header // next byte has alignment 4
487 // something_with_size_5; // next byte has alignment 1
488 // something_with_alignment_8;
489 // which has 7 bytes of padding, as opposed to the naive solution
490 // which might have less (?).
491 if (endAlign < maxFieldAlign) {
492 SmallVectorImpl<BlockLayoutChunk>::iterator
493 li = layout.begin() + 1, le = layout.end();
495 // Look for something that the header end is already
496 // satisfactorily aligned for.
497 for (; li != le && endAlign < li->Alignment; ++li)
500 // If we found something that's naturally aligned for the end of
501 // the header, keep adding things...
503 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
504 for (; li != le; ++li) {
505 assert(endAlign >= li->Alignment);
507 li->setIndex(info, elementTypes.size());
508 elementTypes.push_back(li->Type);
509 blockSize += li->Size;
510 endAlign = getLowBit(blockSize);
512 // ...until we get to the alignment of the maximum field.
513 if (endAlign >= maxFieldAlign) {
515 // No user field was appended. So, a gap was added.
516 // Save total gap size for use in block layout bit map.
517 info.BlockHeaderForcedGapSize = li->Size;
522 // Don't re-append everything we just appended.
523 layout.erase(first, li);
527 assert(endAlign == getLowBit(blockSize));
529 // At this point, we just have to add padding if the end align still
530 // isn't aligned right.
531 if (endAlign < maxFieldAlign) {
532 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
533 CharUnits padding = newBlockSize - blockSize;
535 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
536 padding.getQuantity()));
537 blockSize = newBlockSize;
538 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
541 assert(endAlign >= maxFieldAlign);
542 assert(endAlign == getLowBit(blockSize));
543 // Slam everything else on now. This works because they have
544 // strictly decreasing alignment and we expect that size is always a
545 // multiple of alignment.
546 for (SmallVectorImpl<BlockLayoutChunk>::iterator
547 li = layout.begin(), le = layout.end(); li != le; ++li) {
548 if (endAlign < li->Alignment) {
549 // size may not be multiple of alignment. This can only happen with
550 // an over-aligned variable. We will be adding a padding field to
551 // make the size be multiple of alignment.
552 CharUnits padding = li->Alignment - endAlign;
553 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
554 padding.getQuantity()));
555 blockSize += padding;
556 endAlign = getLowBit(blockSize);
558 assert(endAlign >= li->Alignment);
559 li->setIndex(info, elementTypes.size());
560 elementTypes.push_back(li->Type);
561 blockSize += li->Size;
562 endAlign = getLowBit(blockSize);
566 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
569 /// Enter the scope of a block. This should be run at the entrance to
570 /// a full-expression so that the block's cleanups are pushed at the
571 /// right place in the stack.
572 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
573 assert(CGF.HaveInsertPoint());
575 // Allocate the block info and place it at the head of the list.
576 CGBlockInfo &blockInfo =
577 *new CGBlockInfo(block, CGF.CurFn->getName());
578 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
579 CGF.FirstBlockInfo = &blockInfo;
581 // Compute information about the layout, etc., of this block,
582 // pushing cleanups as necessary.
583 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
585 // Nothing else to do if it can be global.
586 if (blockInfo.CanBeGlobal) return;
588 // Make the allocation for the block.
590 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
591 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
593 // If there are cleanups to emit, enter them (but inactive).
594 if (!blockInfo.NeedsCopyDispose) return;
596 // Walk through the captures (in order) and find the ones not
597 // captured by constant.
598 for (const auto &CI : block->captures()) {
599 // Ignore __block captures; there's nothing special in the
600 // on-stack block that we need to do for them.
601 if (CI.isByRef()) continue;
603 // Ignore variables that are constant-captured.
604 const VarDecl *variable = CI.getVariable();
605 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606 if (capture.isConstant()) continue;
608 // Ignore objects that aren't destructed.
609 QualType::DestructionKind dtorKind =
610 variable->getType().isDestructedType();
611 if (dtorKind == QualType::DK_none) continue;
613 CodeGenFunction::Destroyer *destroyer;
615 // Block captures count as local values and have imprecise semantics.
616 // They also can't be arrays, so need to worry about that.
617 if (dtorKind == QualType::DK_objc_strong_lifetime) {
618 destroyer = CodeGenFunction::destroyARCStrongImprecise;
620 destroyer = CGF.getDestroyer(dtorKind);
623 // GEP down to the address.
624 llvm::Value *addr = CGF.Builder.CreateStructGEP(
625 blockInfo.StructureType, blockInfo.Address, capture.getIndex());
627 // We can use that GEP as the dominating IP.
628 if (!blockInfo.DominatingIP)
629 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
631 CleanupKind cleanupKind = InactiveNormalCleanup;
632 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
633 if (useArrayEHCleanup)
634 cleanupKind = InactiveNormalAndEHCleanup;
636 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
637 destroyer, useArrayEHCleanup);
639 // Remember where that cleanup was.
640 capture.setCleanup(CGF.EHStack.stable_begin());
644 /// Enter a full-expression with a non-trivial number of objects to
645 /// clean up. This is in this file because, at the moment, the only
646 /// kind of cleanup object is a BlockDecl*.
647 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
648 assert(E->getNumObjects() != 0);
649 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
650 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
651 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
652 enterBlockScope(*this, *i);
656 /// Find the layout for the given block in a linked list and remove it.
657 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
658 const BlockDecl *block) {
660 assert(head && *head);
661 CGBlockInfo *cur = *head;
663 // If this is the block we're looking for, splice it out of the list.
664 if (cur->getBlockDecl() == block) {
665 *head = cur->NextBlockInfo;
669 head = &cur->NextBlockInfo;
673 /// Destroy a chain of block layouts.
674 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
675 assert(head && "destroying an empty chain");
677 CGBlockInfo *cur = head;
678 head = cur->NextBlockInfo;
680 } while (head != nullptr);
683 /// Emit a block literal expression in the current function.
684 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
685 // If the block has no captures, we won't have a pre-computed
687 if (!blockExpr->getBlockDecl()->hasCaptures()) {
688 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
689 computeBlockInfo(CGM, this, blockInfo);
690 blockInfo.BlockExpression = blockExpr;
691 return EmitBlockLiteral(blockInfo);
694 // Find the block info for this block and take ownership of it.
695 std::unique_ptr<CGBlockInfo> blockInfo;
696 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
697 blockExpr->getBlockDecl()));
699 blockInfo->BlockExpression = blockExpr;
700 return EmitBlockLiteral(*blockInfo);
703 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
704 // Using the computed layout, generate the actual block function.
705 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
706 llvm::Constant *blockFn
707 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
710 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
712 // If there is nothing to capture, we can emit this as a global block.
713 if (blockInfo.CanBeGlobal)
714 return buildGlobalBlock(CGM, blockInfo, blockFn);
716 // Otherwise, we have to emit this as a local block.
718 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
719 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
721 // Build the block descriptor.
722 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
724 llvm::Type *blockTy = blockInfo.StructureType;
725 llvm::AllocaInst *blockAddr = blockInfo.Address;
726 assert(blockAddr && "block has no address!");
728 // Compute the initial on-stack block flags.
729 BlockFlags flags = BLOCK_HAS_SIGNATURE;
730 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
731 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
732 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
733 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
735 // Initialize the block literal.
737 isa, Builder.CreateStructGEP(blockTy, blockAddr, 0, "block.isa"));
739 llvm::ConstantInt::get(IntTy, flags.getBitMask()),
740 Builder.CreateStructGEP(blockTy, blockAddr, 1, "block.flags"));
742 llvm::ConstantInt::get(IntTy, 0),
743 Builder.CreateStructGEP(blockTy, blockAddr, 2, "block.reserved"));
745 blockFn, Builder.CreateStructGEP(blockTy, blockAddr, 3, "block.invoke"));
746 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockTy, blockAddr, 4,
747 "block.descriptor"));
749 // Finally, capture all the values into the block.
750 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
753 if (blockDecl->capturesCXXThis()) {
754 llvm::Value *addr = Builder.CreateStructGEP(
755 blockTy, blockAddr, blockInfo.CXXThisIndex, "block.captured-this.addr");
756 Builder.CreateStore(LoadCXXThis(), addr);
759 // Next, captured variables.
760 for (const auto &CI : blockDecl->captures()) {
761 const VarDecl *variable = CI.getVariable();
762 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
764 // Ignore constant captures.
765 if (capture.isConstant()) continue;
767 QualType type = variable->getType();
768 CharUnits align = getContext().getDeclAlign(variable);
770 // This will be a [[type]]*, except that a byref entry will just be
772 llvm::Value *blockField = Builder.CreateStructGEP(
773 blockTy, blockAddr, capture.getIndex(), "block.captured");
775 // Compute the address of the thing we're going to move into the
778 if (BlockInfo && CI.isNested()) {
779 // We need to use the capture from the enclosing block.
780 const CGBlockInfo::Capture &enclosingCapture =
781 BlockInfo->getCapture(variable);
783 // This is a [[type]]*, except that a byref entry wil just be an i8**.
784 src = Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
785 enclosingCapture.getIndex(),
786 "block.capture.addr");
787 } else if (blockDecl->isConversionFromLambda()) {
788 // The lambda capture in a lambda's conversion-to-block-pointer is
789 // special; we'll simply emit it directly.
792 // Just look it up in the locals map, which will give us back a
793 // [[type]]*. If that doesn't work, do the more elaborate DRE
795 src = LocalDeclMap.lookup(variable);
798 const_cast<VarDecl *>(variable),
799 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
800 VK_LValue, SourceLocation());
801 src = EmitDeclRefLValue(&declRef).getAddress();
805 // For byrefs, we just write the pointer to the byref struct into
806 // the block field. There's no need to chase the forwarding
807 // pointer at this point, since we're building something that will
808 // live a shorter life than the stack byref anyway.
810 // Get a void* that points to the byref struct.
812 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
815 src = Builder.CreateBitCast(src, VoidPtrTy);
817 // Write that void* into the capture field.
818 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
820 // If we have a copy constructor, evaluate that into the block field.
821 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
822 if (blockDecl->isConversionFromLambda()) {
823 // If we have a lambda conversion, emit the expression
824 // directly into the block instead.
826 AggValueSlot::forAddr(blockField, align, Qualifiers(),
827 AggValueSlot::IsDestructed,
828 AggValueSlot::DoesNotNeedGCBarriers,
829 AggValueSlot::IsNotAliased);
830 EmitAggExpr(copyExpr, Slot);
832 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
835 // If it's a reference variable, copy the reference into the block field.
836 } else if (type->isReferenceType()) {
838 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
839 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
841 // If this is an ARC __strong block-pointer variable, don't do a
844 // TODO: this can be generalized into the normal initialization logic:
845 // we should never need to do a block-copy when initializing a local
846 // variable, because the local variable's lifetime should be strictly
847 // contained within the stack block's.
848 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
849 type->isBlockPointerType()) {
850 // Load the block and do a simple retain.
851 LValue srcLV = MakeAddrLValue(src, type, align);
852 llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
853 value = EmitARCRetainNonBlock(value);
855 // Do a primitive store to the block field.
856 LValue destLV = MakeAddrLValue(blockField, type, align);
857 EmitStoreOfScalar(value, destLV, /*init*/ true);
859 // Otherwise, fake up a POD copy into the block field.
861 // Fake up a new variable so that EmitScalarInit doesn't think
862 // we're referring to the variable in its own initializer.
863 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
864 SourceLocation(), /*name*/ nullptr,
867 // We use one of these or the other depending on whether the
868 // reference is nested.
869 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
870 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
871 type, VK_LValue, SourceLocation());
873 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
874 &declRef, VK_RValue);
875 // FIXME: Pass a specific location for the expr init so that the store is
876 // attributed to a reasonable location - otherwise it may be attributed to
877 // locations of subexpressions in the initialization.
878 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
879 MakeAddrLValue(blockField, type, align),
880 /*captured by init*/ false);
883 // Activate the cleanup if layout pushed one.
885 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
886 if (cleanup.isValid())
887 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
891 // Cast to the converted block-pointer type, which happens (somewhat
892 // unfortunately) to be a pointer to function type.
893 llvm::Value *result =
894 Builder.CreateBitCast(blockAddr,
895 ConvertType(blockInfo.getBlockExpr()->getType()));
901 llvm::Type *CodeGenModule::getBlockDescriptorType() {
902 if (BlockDescriptorType)
903 return BlockDescriptorType;
905 llvm::Type *UnsignedLongTy =
906 getTypes().ConvertType(getContext().UnsignedLongTy);
908 // struct __block_descriptor {
909 // unsigned long reserved;
910 // unsigned long block_size;
912 // // later, the following will be added
915 // void (*copyHelper)();
916 // void (*copyHelper)();
917 // } helpers; // !!! optional
919 // const char *signature; // the block signature
920 // const char *layout; // reserved
922 BlockDescriptorType =
923 llvm::StructType::create("struct.__block_descriptor",
924 UnsignedLongTy, UnsignedLongTy, nullptr);
926 // Now form a pointer to that.
927 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
928 return BlockDescriptorType;
931 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
932 if (GenericBlockLiteralType)
933 return GenericBlockLiteralType;
935 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
937 // struct __block_literal_generic {
941 // void (*__invoke)(void *);
942 // struct __block_descriptor *__descriptor;
944 GenericBlockLiteralType =
945 llvm::StructType::create("struct.__block_literal_generic",
946 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
947 BlockDescPtrTy, nullptr);
949 return GenericBlockLiteralType;
953 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
954 ReturnValueSlot ReturnValue) {
955 const BlockPointerType *BPT =
956 E->getCallee()->getType()->getAs<BlockPointerType>();
958 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
960 // Get a pointer to the generic block literal.
961 llvm::Type *BlockLiteralTy =
962 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
964 // Bitcast the callee to a block literal.
965 llvm::Value *BlockLiteral =
966 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
968 // Get the function pointer from the literal.
969 llvm::Value *FuncPtr = Builder.CreateStructGEP(
970 CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
972 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
974 // Add the block literal.
976 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
978 QualType FnType = BPT->getPointeeType();
980 // And the rest of the arguments.
981 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
982 E->arg_begin(), E->arg_end());
984 // Load the function.
985 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
987 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
988 const CGFunctionInfo &FnInfo =
989 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
991 // Cast the function pointer to the right type.
992 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
994 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
995 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
997 // And call the block.
998 return EmitCall(FnInfo, Func, ReturnValue, Args);
1001 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1003 assert(BlockInfo && "evaluating block ref without block information?");
1004 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
1006 // Handle constant captures.
1007 if (capture.isConstant()) return LocalDeclMap[variable];
1010 Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
1011 capture.getIndex(), "block.capture.addr");
1014 // addr should be a void** right now. Load, then cast the result
1017 addr = Builder.CreateLoad(addr);
1018 auto *byrefType = BuildByRefType(variable);
1019 llvm::PointerType *byrefPointerType = llvm::PointerType::get(byrefType, 0);
1020 addr = Builder.CreateBitCast(addr, byrefPointerType,
1023 // Follow the forwarding pointer.
1024 addr = Builder.CreateStructGEP(byrefType, addr, 1, "byref.forwarding");
1025 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
1027 // Cast back to byref* and GEP over to the actual object.
1028 addr = Builder.CreateBitCast(addr, byrefPointerType);
1029 addr = Builder.CreateStructGEP(byrefType, addr,
1030 getByRefValueLLVMField(variable).second,
1031 variable->getNameAsString());
1034 if (variable->getType()->isReferenceType())
1035 addr = Builder.CreateLoad(addr, "ref.tmp");
1041 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
1043 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1044 blockInfo.BlockExpression = blockExpr;
1046 // Compute information about the layout, etc., of this block.
1047 computeBlockInfo(*this, nullptr, blockInfo);
1049 // Using that metadata, generate the actual block function.
1050 llvm::Constant *blockFn;
1052 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
1053 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1058 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
1060 return buildGlobalBlock(*this, blockInfo, blockFn);
1063 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1064 const CGBlockInfo &blockInfo,
1065 llvm::Constant *blockFn) {
1066 assert(blockInfo.CanBeGlobal);
1068 // Generate the constants for the block literal initializer.
1069 llvm::Constant *fields[BlockHeaderSize];
1072 fields[0] = CGM.getNSConcreteGlobalBlock();
1075 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1076 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1078 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
1081 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
1084 fields[3] = blockFn;
1087 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1089 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1091 llvm::GlobalVariable *literal =
1092 new llvm::GlobalVariable(CGM.getModule(),
1095 llvm::GlobalVariable::InternalLinkage,
1097 "__block_literal_global");
1098 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1100 // Return a constant of the appropriately-casted type.
1101 llvm::Type *requiredType =
1102 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1103 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1107 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1108 const CGBlockInfo &blockInfo,
1109 const DeclMapTy &ldm,
1110 bool IsLambdaConversionToBlock) {
1111 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1115 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
1117 BlockInfo = &blockInfo;
1119 // Arrange for local static and local extern declarations to appear
1120 // to be local to this function as well, in case they're directly
1121 // referenced in a block.
1122 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1123 const auto *var = dyn_cast<VarDecl>(i->first);
1124 if (var && !var->hasLocalStorage())
1125 LocalDeclMap[var] = i->second;
1128 // Begin building the function declaration.
1130 // Build the argument list.
1131 FunctionArgList args;
1133 // The first argument is the block pointer. Just take it as a void*
1134 // and cast it later.
1135 QualType selfTy = getContext().VoidPtrTy;
1136 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1138 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
1139 SourceLocation(), II, selfTy);
1140 args.push_back(&selfDecl);
1142 // Now add the rest of the parameters.
1143 args.append(blockDecl->param_begin(), blockDecl->param_end());
1145 // Create the function declaration.
1146 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1147 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
1148 fnType->getReturnType(), args, fnType->getExtInfo(),
1149 fnType->isVariadic());
1150 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
1151 blockInfo.UsesStret = true;
1153 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1155 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
1156 llvm::Function *fn = llvm::Function::Create(
1157 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
1158 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1160 // Begin generating the function.
1161 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
1162 blockDecl->getLocation(),
1163 blockInfo.getBlockExpr()->getBody()->getLocStart());
1165 // Okay. Undo some of what StartFunction did.
1167 // Pull the 'self' reference out of the local decl map.
1168 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1169 LocalDeclMap.erase(&selfDecl);
1170 BlockPointer = Builder.CreateBitCast(blockAddr,
1171 blockInfo.StructureType->getPointerTo(),
1173 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1174 // won't delete the dbg.declare intrinsics for captured variables.
1175 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1176 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1177 // Allocate a stack slot for it, so we can point the debugger to it
1178 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1180 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1181 Alloca->setAlignment(Align);
1182 // Set the DebugLocation to empty, so the store is recognized as a
1183 // frame setup instruction by llvm::DwarfDebug::beginFunction().
1184 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1185 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1186 BlockPointerDbgLoc = Alloca;
1189 // If we have a C++ 'this' reference, go ahead and force it into
1191 if (blockDecl->capturesCXXThis()) {
1193 Builder.CreateStructGEP(blockInfo.StructureType, BlockPointer,
1194 blockInfo.CXXThisIndex, "block.captured-this");
1195 CXXThisValue = Builder.CreateLoad(addr, "this");
1198 // Also force all the constant captures.
1199 for (const auto &CI : blockDecl->captures()) {
1200 const VarDecl *variable = CI.getVariable();
1201 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1202 if (!capture.isConstant()) continue;
1204 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1206 llvm::AllocaInst *alloca =
1207 CreateMemTemp(variable->getType(), "block.captured-const");
1208 alloca->setAlignment(align);
1210 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
1212 LocalDeclMap[variable] = alloca;
1215 // Save a spot to insert the debug information for all the DeclRefExprs.
1216 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1217 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1220 if (IsLambdaConversionToBlock)
1221 EmitLambdaBlockInvokeBody();
1223 PGO.assignRegionCounters(blockDecl, fn);
1224 incrementProfileCounter(blockDecl->getBody());
1225 EmitStmt(blockDecl->getBody());
1228 // Remember where we were...
1229 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1231 // Go back to the entry.
1233 Builder.SetInsertPoint(entry, entry_ptr);
1235 // Emit debug information for all the DeclRefExprs.
1236 // FIXME: also for 'this'
1237 if (CGDebugInfo *DI = getDebugInfo()) {
1238 for (const auto &CI : blockDecl->captures()) {
1239 const VarDecl *variable = CI.getVariable();
1240 DI->EmitLocation(Builder, variable->getLocation());
1242 if (CGM.getCodeGenOpts().getDebugInfo()
1243 >= CodeGenOptions::LimitedDebugInfo) {
1244 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1245 if (capture.isConstant()) {
1246 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1251 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
1253 entry_ptr == entry->end()
1254 ? nullptr : entry_ptr);
1257 // Recover location if it was changed in the above loop.
1258 DI->EmitLocation(Builder,
1259 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1262 // And resume where we left off.
1263 if (resume == nullptr)
1264 Builder.ClearInsertionPoint();
1266 Builder.SetInsertPoint(resume);
1268 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1274 notes.push_back(HelperInfo());
1275 HelperInfo ¬e = notes.back();
1276 note.index = capture.getIndex();
1277 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1278 note.cxxbar_import = ci->getCopyExpr();
1280 if (ci->isByRef()) {
1281 note.flag = BLOCK_FIELD_IS_BYREF;
1282 if (type.isObjCGCWeak())
1283 note.flag |= BLOCK_FIELD_IS_WEAK;
1284 } else if (type->isBlockPointerType()) {
1285 note.flag = BLOCK_FIELD_IS_BLOCK;
1287 note.flag = BLOCK_FIELD_IS_OBJECT;
1292 /// Generate the copy-helper function for a block closure object:
1293 /// static void block_copy_helper(block_t *dst, block_t *src);
1294 /// The runtime will have previously initialized 'dst' by doing a
1295 /// bit-copy of 'src'.
1297 /// Note that this copies an entire block closure object to the heap;
1298 /// it should not be confused with a 'byref copy helper', which moves
1299 /// the contents of an individual __block variable to the heap.
1301 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1302 ASTContext &C = getContext();
1304 FunctionArgList args;
1305 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1307 args.push_back(&dstDecl);
1308 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1310 args.push_back(&srcDecl);
1312 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1313 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1315 // FIXME: it would be nice if these were mergeable with things with
1316 // identical semantics.
1317 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1319 llvm::Function *Fn =
1320 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1321 "__copy_helper_block_", &CGM.getModule());
1324 = &CGM.getContext().Idents.get("__copy_helper_block_");
1326 FunctionDecl *FD = FunctionDecl::Create(C,
1327 C.getTranslationUnitDecl(),
1329 SourceLocation(), II, C.VoidTy,
1333 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1334 StartFunction(FD, C.VoidTy, Fn, FI, args);
1335 // Create a scope with an artificial location for the body of this function.
1336 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1337 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1339 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1340 src = Builder.CreateLoad(src);
1341 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1343 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1344 dst = Builder.CreateLoad(dst);
1345 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1347 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1349 for (const auto &CI : blockDecl->captures()) {
1350 const VarDecl *variable = CI.getVariable();
1351 QualType type = variable->getType();
1353 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1354 if (capture.isConstant()) continue;
1356 const Expr *copyExpr = CI.getCopyExpr();
1357 BlockFieldFlags flags;
1359 bool useARCWeakCopy = false;
1360 bool useARCStrongCopy = false;
1363 assert(!CI.isByRef());
1364 // don't bother computing flags
1366 } else if (CI.isByRef()) {
1367 flags = BLOCK_FIELD_IS_BYREF;
1368 if (type.isObjCGCWeak())
1369 flags |= BLOCK_FIELD_IS_WEAK;
1371 } else if (type->isObjCRetainableType()) {
1372 flags = BLOCK_FIELD_IS_OBJECT;
1373 bool isBlockPointer = type->isBlockPointerType();
1375 flags = BLOCK_FIELD_IS_BLOCK;
1377 // Special rules for ARC captures:
1378 if (getLangOpts().ObjCAutoRefCount) {
1379 Qualifiers qs = type.getQualifiers();
1381 // We need to register __weak direct captures with the runtime.
1382 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1383 useARCWeakCopy = true;
1385 // We need to retain the copied value for __strong direct captures.
1386 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1387 // If it's a block pointer, we have to copy the block and
1388 // assign that to the destination pointer, so we might as
1389 // well use _Block_object_assign. Otherwise we can avoid that.
1390 if (!isBlockPointer)
1391 useARCStrongCopy = true;
1393 // Otherwise the memcpy is fine.
1398 // Non-ARC captures of retainable pointers are strong and
1399 // therefore require a call to _Block_object_assign.
1407 unsigned index = capture.getIndex();
1408 llvm::Value *srcField =
1409 Builder.CreateStructGEP(blockInfo.StructureType, src, index);
1410 llvm::Value *dstField =
1411 Builder.CreateStructGEP(blockInfo.StructureType, dst, index);
1413 // If there's an explicit copy expression, we do that.
1415 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1416 } else if (useARCWeakCopy) {
1417 EmitARCCopyWeak(dstField, srcField);
1419 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1420 if (useARCStrongCopy) {
1421 // At -O0, store null into the destination field (so that the
1422 // storeStrong doesn't over-release) and then call storeStrong.
1423 // This is a workaround to not having an initStrong call.
1424 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1425 auto *ty = cast<llvm::PointerType>(srcValue->getType());
1426 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1427 Builder.CreateStore(null, dstField);
1428 EmitARCStoreStrongCall(dstField, srcValue, true);
1430 // With optimization enabled, take advantage of the fact that
1431 // the blocks runtime guarantees a memcpy of the block data, and
1432 // just emit a retain of the src field.
1434 EmitARCRetainNonBlock(srcValue);
1436 // We don't need this anymore, so kill it. It's not quite
1437 // worth the annoyance to avoid creating it in the first place.
1438 cast<llvm::Instruction>(dstField)->eraseFromParent();
1441 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1442 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1443 llvm::Value *args[] = {
1444 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1447 bool copyCanThrow = false;
1448 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
1449 const Expr *copyExpr =
1450 CGM.getContext().getBlockVarCopyInits(variable);
1452 copyCanThrow = true; // FIXME: reuse the noexcept logic
1457 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1459 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1467 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1470 /// Generate the destroy-helper function for a block closure object:
1471 /// static void block_destroy_helper(block_t *theBlock);
1473 /// Note that this destroys a heap-allocated block closure object;
1474 /// it should not be confused with a 'byref destroy helper', which
1475 /// destroys the heap-allocated contents of an individual __block
1478 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1479 ASTContext &C = getContext();
1481 FunctionArgList args;
1482 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1484 args.push_back(&srcDecl);
1486 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1487 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
1489 // FIXME: We'd like to put these into a mergable by content, with
1490 // internal linkage.
1491 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1493 llvm::Function *Fn =
1494 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1495 "__destroy_helper_block_", &CGM.getModule());
1498 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1500 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1502 SourceLocation(), II, C.VoidTy,
1505 // Create a scope with an artificial location for the body of this function.
1506 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1507 StartFunction(FD, C.VoidTy, Fn, FI, args);
1508 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1510 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1512 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1513 src = Builder.CreateLoad(src);
1514 src = Builder.CreateBitCast(src, structPtrTy, "block");
1516 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1518 CodeGenFunction::RunCleanupsScope cleanups(*this);
1520 for (const auto &CI : blockDecl->captures()) {
1521 const VarDecl *variable = CI.getVariable();
1522 QualType type = variable->getType();
1524 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1525 if (capture.isConstant()) continue;
1527 BlockFieldFlags flags;
1528 const CXXDestructorDecl *dtor = nullptr;
1530 bool useARCWeakDestroy = false;
1531 bool useARCStrongDestroy = false;
1534 flags = BLOCK_FIELD_IS_BYREF;
1535 if (type.isObjCGCWeak())
1536 flags |= BLOCK_FIELD_IS_WEAK;
1537 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1538 if (record->hasTrivialDestructor())
1540 dtor = record->getDestructor();
1541 } else if (type->isObjCRetainableType()) {
1542 flags = BLOCK_FIELD_IS_OBJECT;
1543 if (type->isBlockPointerType())
1544 flags = BLOCK_FIELD_IS_BLOCK;
1546 // Special rules for ARC captures.
1547 if (getLangOpts().ObjCAutoRefCount) {
1548 Qualifiers qs = type.getQualifiers();
1550 // Don't generate special dispose logic for a captured object
1551 // unless it's __strong or __weak.
1552 if (!qs.hasStrongOrWeakObjCLifetime())
1555 // Support __weak direct captures.
1556 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1557 useARCWeakDestroy = true;
1559 // Tools really want us to use objc_storeStrong here.
1561 useARCStrongDestroy = true;
1567 unsigned index = capture.getIndex();
1568 llvm::Value *srcField =
1569 Builder.CreateStructGEP(blockInfo.StructureType, src, index);
1571 // If there's an explicit copy expression, we do that.
1573 PushDestructorCleanup(dtor, srcField);
1575 // If this is a __weak capture, emit the release directly.
1576 } else if (useARCWeakDestroy) {
1577 EmitARCDestroyWeak(srcField);
1579 // Destroy strong objects with a call if requested.
1580 } else if (useARCStrongDestroy) {
1581 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
1583 // Otherwise we call _Block_object_dispose. It wouldn't be too
1584 // hard to just emit this as a cleanup if we wanted to make sure
1585 // that things were done in reverse.
1587 llvm::Value *value = Builder.CreateLoad(srcField);
1588 value = Builder.CreateBitCast(value, VoidPtrTy);
1589 BuildBlockRelease(value, flags);
1593 cleanups.ForceCleanup();
1597 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1602 /// Emits the copy/dispose helper functions for a __block object of id type.
1603 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1604 BlockFieldFlags Flags;
1607 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1608 : ByrefHelpers(alignment), Flags(flags) {}
1610 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1611 llvm::Value *srcField) override {
1612 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1614 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1615 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1617 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1619 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1620 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1622 llvm::Value *args[] = { destField, srcValue, flagsVal };
1623 CGF.EmitNounwindRuntimeCall(fn, args);
1626 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1627 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1628 llvm::Value *value = CGF.Builder.CreateLoad(field);
1630 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1633 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1634 id.AddInteger(Flags.getBitMask());
1638 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1639 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1641 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1643 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1644 llvm::Value *srcField) override {
1645 CGF.EmitARCMoveWeak(destField, srcField);
1648 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1649 CGF.EmitARCDestroyWeak(field);
1652 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1653 // 0 is distinguishable from all pointers and byref flags
1658 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1659 /// that's not of block-pointer type.
1660 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1662 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1664 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1665 llvm::Value *srcField) override {
1666 // Do a "move" by copying the value and then zeroing out the old
1669 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1670 value->setAlignment(Alignment.getQuantity());
1673 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1675 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
1676 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1677 store->setAlignment(Alignment.getQuantity());
1678 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1679 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1682 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1683 store->setAlignment(Alignment.getQuantity());
1685 store = CGF.Builder.CreateStore(null, srcField);
1686 store->setAlignment(Alignment.getQuantity());
1689 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1690 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1693 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1694 // 1 is distinguishable from all pointers and byref flags
1699 /// Emits the copy/dispose helpers for an ARC __block __strong
1700 /// variable that's of block-pointer type.
1701 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1703 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1705 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1706 llvm::Value *srcField) override {
1707 // Do the copy with objc_retainBlock; that's all that
1708 // _Block_object_assign would do anyway, and we'd have to pass the
1709 // right arguments to make sure it doesn't get no-op'ed.
1710 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1711 oldValue->setAlignment(Alignment.getQuantity());
1713 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1715 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1716 store->setAlignment(Alignment.getQuantity());
1719 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1720 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
1723 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1724 // 2 is distinguishable from all pointers and byref flags
1729 /// Emits the copy/dispose helpers for a __block variable with a
1730 /// nontrivial copy constructor or destructor.
1731 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1733 const Expr *CopyExpr;
1736 CXXByrefHelpers(CharUnits alignment, QualType type,
1737 const Expr *copyExpr)
1738 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1740 bool needsCopy() const override { return CopyExpr != nullptr; }
1741 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1742 llvm::Value *srcField) override {
1743 if (!CopyExpr) return;
1744 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1747 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
1748 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1749 CGF.PushDestructorCleanup(VarType, field);
1750 CGF.PopCleanupBlocks(cleanupDepth);
1753 void profileImpl(llvm::FoldingSetNodeID &id) const override {
1754 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1757 } // end anonymous namespace
1759 static llvm::Constant *
1760 generateByrefCopyHelper(CodeGenFunction &CGF,
1761 llvm::StructType &byrefType,
1762 unsigned valueFieldIndex,
1763 CodeGenModule::ByrefHelpers &byrefInfo) {
1764 ASTContext &Context = CGF.getContext();
1766 QualType R = Context.VoidTy;
1768 FunctionArgList args;
1769 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1771 args.push_back(&dst);
1773 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1775 args.push_back(&src);
1777 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1778 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1780 CodeGenTypes &Types = CGF.CGM.getTypes();
1781 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1783 // FIXME: We'd like to put these into a mergable by content, with
1784 // internal linkage.
1785 llvm::Function *Fn =
1786 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1787 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1790 = &Context.Idents.get("__Block_byref_object_copy_");
1792 FunctionDecl *FD = FunctionDecl::Create(Context,
1793 Context.getTranslationUnitDecl(),
1795 SourceLocation(), II, R, nullptr,
1799 CGF.StartFunction(FD, R, Fn, FI, args);
1801 if (byrefInfo.needsCopy()) {
1802 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1805 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1806 destField = CGF.Builder.CreateLoad(destField);
1807 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1808 destField = CGF.Builder.CreateStructGEP(&byrefType, destField,
1809 valueFieldIndex, "x");
1812 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1813 srcField = CGF.Builder.CreateLoad(srcField);
1814 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1816 CGF.Builder.CreateStructGEP(&byrefType, srcField, valueFieldIndex, "x");
1818 byrefInfo.emitCopy(CGF, destField, srcField);
1821 CGF.FinishFunction();
1823 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1826 /// Build the copy helper for a __block variable.
1827 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1828 llvm::StructType &byrefType,
1829 unsigned byrefValueIndex,
1830 CodeGenModule::ByrefHelpers &info) {
1831 CodeGenFunction CGF(CGM);
1832 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
1835 /// Generate code for a __block variable's dispose helper.
1836 static llvm::Constant *
1837 generateByrefDisposeHelper(CodeGenFunction &CGF,
1838 llvm::StructType &byrefType,
1839 unsigned byrefValueIndex,
1840 CodeGenModule::ByrefHelpers &byrefInfo) {
1841 ASTContext &Context = CGF.getContext();
1842 QualType R = Context.VoidTy;
1844 FunctionArgList args;
1845 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
1847 args.push_back(&src);
1849 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1850 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
1852 CodeGenTypes &Types = CGF.CGM.getTypes();
1853 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1855 // FIXME: We'd like to put these into a mergable by content, with
1856 // internal linkage.
1857 llvm::Function *Fn =
1858 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1859 "__Block_byref_object_dispose_",
1860 &CGF.CGM.getModule());
1863 = &Context.Idents.get("__Block_byref_object_dispose_");
1865 FunctionDecl *FD = FunctionDecl::Create(Context,
1866 Context.getTranslationUnitDecl(),
1868 SourceLocation(), II, R, nullptr,
1871 CGF.StartFunction(FD, R, Fn, FI, args);
1873 if (byrefInfo.needsDispose()) {
1874 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1875 V = CGF.Builder.CreateLoad(V);
1876 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1877 V = CGF.Builder.CreateStructGEP(&byrefType, V, byrefValueIndex, "x");
1879 byrefInfo.emitDispose(CGF, V);
1882 CGF.FinishFunction();
1884 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1887 /// Build the dispose helper for a __block variable.
1888 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1889 llvm::StructType &byrefType,
1890 unsigned byrefValueIndex,
1891 CodeGenModule::ByrefHelpers &info) {
1892 CodeGenFunction CGF(CGM);
1893 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
1896 /// Lazily build the copy and dispose helpers for a __block variable
1897 /// with the given information.
1898 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1899 llvm::StructType &byrefTy,
1900 unsigned byrefValueIndex,
1902 // Increase the field's alignment to be at least pointer alignment,
1903 // since the layout of the byref struct will guarantee at least that.
1904 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1905 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1907 llvm::FoldingSetNodeID id;
1908 byrefInfo.Profile(id);
1911 CodeGenModule::ByrefHelpers *node
1912 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1913 if (node) return static_cast<T*>(node);
1915 byrefInfo.CopyHelper =
1916 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1917 byrefInfo.DisposeHelper =
1918 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
1920 T *copy = new (CGM.getContext()) T(byrefInfo);
1921 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1925 /// Build the copy and dispose helpers for the given __block variable
1926 /// emission. Places the helpers in the global cache. Returns null
1927 /// if no helpers are required.
1928 CodeGenModule::ByrefHelpers *
1929 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1930 const AutoVarEmission &emission) {
1931 const VarDecl &var = *emission.Variable;
1932 QualType type = var.getType();
1934 unsigned byrefValueIndex = getByRefValueLLVMField(&var).second;
1936 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1937 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1938 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
1940 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1941 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1944 // Otherwise, if we don't have a retainable type, there's nothing to do.
1945 // that the runtime does extra copies.
1946 if (!type->isObjCRetainableType()) return nullptr;
1948 Qualifiers qs = type.getQualifiers();
1950 // If we have lifetime, that dominates.
1951 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1952 assert(getLangOpts().ObjCAutoRefCount);
1955 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1957 // These are just bits as far as the runtime is concerned.
1958 case Qualifiers::OCL_ExplicitNone:
1959 case Qualifiers::OCL_Autoreleasing:
1962 // Tell the runtime that this is ARC __weak, called by the
1964 case Qualifiers::OCL_Weak: {
1965 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1966 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1969 // ARC __strong __block variables need to be retained.
1970 case Qualifiers::OCL_Strong:
1971 // Block pointers need to be copied, and there's no direct
1972 // transfer possible.
1973 if (type->isBlockPointerType()) {
1974 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1975 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1977 // Otherwise, we transfer ownership of the retain from the stack
1980 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1981 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
1984 llvm_unreachable("fell out of lifetime switch!");
1987 BlockFieldFlags flags;
1988 if (type->isBlockPointerType()) {
1989 flags |= BLOCK_FIELD_IS_BLOCK;
1990 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1991 type->isObjCObjectPointerType()) {
1992 flags |= BLOCK_FIELD_IS_OBJECT;
1997 if (type.isObjCGCWeak())
1998 flags |= BLOCK_FIELD_IS_WEAK;
2000 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
2001 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
2004 std::pair<llvm::Type *, unsigned>
2005 CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
2006 assert(ByRefValueInfo.count(VD) && "Did not find value!");
2008 return ByRefValueInfo.find(VD)->second;
2011 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2013 auto P = getByRefValueLLVMField(V);
2015 Builder.CreateStructGEP(P.first, BaseAddr, 1, "forwarding");
2016 Loc = Builder.CreateLoad(Loc);
2017 Loc = Builder.CreateStructGEP(P.first, Loc, P.second, V->getNameAsString());
2021 /// BuildByRefType - This routine changes a __block variable declared as T x
2026 /// void *__forwarding;
2027 /// int32_t __flags;
2029 /// void *__copy_helper; // only if needed
2030 /// void *__destroy_helper; // only if needed
2031 /// void *__byref_variable_layout;// only if needed
2032 /// char padding[X]; // only if needed
2036 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2037 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
2041 QualType Ty = D->getType();
2043 SmallVector<llvm::Type *, 8> types;
2045 llvm::StructType *ByRefType =
2046 llvm::StructType::create(getLLVMContext(),
2047 "struct.__block_byref_" + D->getNameAsString());
2050 types.push_back(Int8PtrTy);
2052 // void *__forwarding;
2053 types.push_back(llvm::PointerType::getUnqual(ByRefType));
2056 types.push_back(Int32Ty);
2059 types.push_back(Int32Ty);
2060 // Note that this must match *exactly* the logic in buildByrefHelpers.
2061 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2062 if (HasCopyAndDispose) {
2063 /// void *__copy_helper;
2064 types.push_back(Int8PtrTy);
2066 /// void *__destroy_helper;
2067 types.push_back(Int8PtrTy);
2069 bool HasByrefExtendedLayout = false;
2070 Qualifiers::ObjCLifetime Lifetime;
2071 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2072 HasByrefExtendedLayout)
2073 /// void *__byref_variable_layout;
2074 types.push_back(Int8PtrTy);
2076 bool Packed = false;
2077 CharUnits Align = getContext().getDeclAlign(D);
2079 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
2080 // We have to insert padding.
2082 // The struct above has 2 32-bit integers.
2083 unsigned CurrentOffsetInBytes = 4 * 2;
2085 // And either 2, 3, 4 or 5 pointers.
2086 unsigned noPointers = 2;
2087 if (HasCopyAndDispose)
2089 if (HasByrefExtendedLayout)
2092 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
2094 // Align the offset.
2095 unsigned AlignedOffsetInBytes =
2096 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2098 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2099 if (NumPaddingBytes > 0) {
2100 llvm::Type *Ty = Int8Ty;
2101 // FIXME: We need a sema error for alignment larger than the minimum of
2102 // the maximal stack alignment and the alignment of malloc on the system.
2103 if (NumPaddingBytes > 1)
2104 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2106 types.push_back(Ty);
2108 // We want a packed struct.
2114 types.push_back(ConvertTypeForMem(Ty));
2116 ByRefType->setBody(types, Packed);
2118 Info.first = ByRefType;
2120 Info.second = types.size() - 1;
2125 /// Initialize the structural components of a __block variable, i.e.
2126 /// everything but the actual object.
2127 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
2128 // Find the address of the local.
2129 llvm::Value *addr = emission.Address;
2131 // That's an alloca of the byref structure type.
2132 llvm::StructType *byrefType = cast<llvm::StructType>(
2133 cast<llvm::PointerType>(addr->getType())->getElementType());
2135 // Build the byref helpers if necessary. This is null if we don't need any.
2136 CodeGenModule::ByrefHelpers *helpers =
2137 buildByrefHelpers(*byrefType, emission);
2139 const VarDecl &D = *emission.Variable;
2140 QualType type = D.getType();
2142 bool HasByrefExtendedLayout;
2143 Qualifiers::ObjCLifetime ByrefLifetime;
2144 bool ByRefHasLifetime =
2145 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2149 // Initialize the 'isa', which is just 0 or 1.
2151 if (type.isObjCGCWeak())
2153 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2154 Builder.CreateStore(V,
2155 Builder.CreateStructGEP(nullptr, addr, 0, "byref.isa"));
2157 // Store the address of the variable into its own forwarding pointer.
2158 Builder.CreateStore(
2159 addr, Builder.CreateStructGEP(nullptr, addr, 1, "byref.forwarding"));
2162 // c) the flags field is set to either 0 if no helper functions are
2163 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
2165 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2166 if (ByRefHasLifetime) {
2167 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2168 else switch (ByrefLifetime) {
2169 case Qualifiers::OCL_Strong:
2170 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2172 case Qualifiers::OCL_Weak:
2173 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2175 case Qualifiers::OCL_ExplicitNone:
2176 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2178 case Qualifiers::OCL_None:
2179 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2180 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2185 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2186 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2187 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2188 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2189 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2190 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2191 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2192 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2193 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2194 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2195 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2196 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2197 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2198 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2199 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2200 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2206 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2207 Builder.CreateStructGEP(nullptr, addr, 2, "byref.flags"));
2209 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2210 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2211 Builder.CreateStore(V,
2212 Builder.CreateStructGEP(nullptr, addr, 3, "byref.size"));
2215 llvm::Value *copy_helper = Builder.CreateStructGEP(nullptr, addr, 4);
2216 Builder.CreateStore(helpers->CopyHelper, copy_helper);
2218 llvm::Value *destroy_helper = Builder.CreateStructGEP(nullptr, addr, 5);
2219 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2221 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2222 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2223 llvm::Value *ByrefInfoAddr =
2224 Builder.CreateStructGEP(nullptr, addr, helpers ? 6 : 4, "byref.layout");
2225 // cast destination to pointer to source type.
2226 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2227 DesTy = DesTy->getPointerTo();
2228 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2229 Builder.CreateStore(ByrefLayoutInfo, BC);
2233 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2234 llvm::Value *F = CGM.getBlockObjectDispose();
2235 llvm::Value *args[] = {
2236 Builder.CreateBitCast(V, Int8PtrTy),
2237 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2239 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
2243 struct CallBlockRelease : EHScopeStack::Cleanup {
2245 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2247 void Emit(CodeGenFunction &CGF, Flags flags) override {
2248 // Should we be passing FIELD_IS_WEAK here?
2249 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2254 /// Enter a cleanup to destroy a __block variable. Note that this
2255 /// cleanup should be a no-op if the variable hasn't left the stack
2256 /// yet; if a cleanup is required for the variable itself, that needs
2257 /// to be done externally.
2258 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2259 // We don't enter this cleanup if we're in pure-GC mode.
2260 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2263 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2266 /// Adjust the declaration of something from the blocks API.
2267 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2268 llvm::Constant *C) {
2269 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2271 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2272 if (GV->isDeclaration() && GV->hasExternalLinkage())
2273 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2276 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2277 if (BlockObjectDispose)
2278 return BlockObjectDispose;
2280 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2281 llvm::FunctionType *fty
2282 = llvm::FunctionType::get(VoidTy, args, false);
2283 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2284 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2285 return BlockObjectDispose;
2288 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2289 if (BlockObjectAssign)
2290 return BlockObjectAssign;
2292 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2293 llvm::FunctionType *fty
2294 = llvm::FunctionType::get(VoidTy, args, false);
2295 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2296 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2297 return BlockObjectAssign;
2300 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2301 if (NSConcreteGlobalBlock)
2302 return NSConcreteGlobalBlock;
2304 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2305 Int8PtrTy->getPointerTo(),
2307 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2308 return NSConcreteGlobalBlock;
2311 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2312 if (NSConcreteStackBlock)
2313 return NSConcreteStackBlock;
2315 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2316 Int8PtrTy->getPointerTo(),
2318 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2319 return NSConcreteStackBlock;