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 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenModule.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/DataLayout.h"
25 using namespace clang;
26 using namespace CodeGen;
28 CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
30 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
31 StructureType(0), Block(block),
34 // Skip asm prefix, if any. 'name' is usually taken directly from
35 // the mangled name of the enclosing function.
36 if (!name.empty() && name[0] == '\01')
37 name = name.substr(1);
40 // Anchor the vtable to this translation unit.
41 CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
43 /// Build the given block as a global block.
44 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
45 const CGBlockInfo &blockInfo,
46 llvm::Constant *blockFn);
48 /// Build the helper function to copy a block.
49 static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
50 const CGBlockInfo &blockInfo) {
51 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54 /// Build the helper function to dipose of a block.
55 static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60 /// buildBlockDescriptor - Build the block descriptor meta-data for a block.
61 /// buildBlockDescriptor is accessed from 5th field of the Block_literal
62 /// meta-data and contains stationary information about the block literal.
63 /// Its definition will have 4 (or optinally 6) words.
64 /// struct Block_descriptor {
65 /// unsigned long reserved;
66 /// unsigned long size; // size of Block_literal metadata in bytes.
67 /// void *copy_func_helper_decl; // optional copy helper.
68 /// void *destroy_func_decl; // optioanl destructor helper.
69 /// void *block_method_encoding_address;//@encode for block literal signature.
70 /// void *block_layout_info; // encoding of captured block variables.
72 static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
73 const CGBlockInfo &blockInfo) {
74 ASTContext &C = CGM.getContext();
76 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
77 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
79 SmallVector<llvm::Constant*, 6> elements;
82 elements.push_back(llvm::ConstantInt::get(ulong, 0));
85 // FIXME: What is the right way to say this doesn't fit? We should give
86 // a user diagnostic in that case. Better fix would be to change the
88 elements.push_back(llvm::ConstantInt::get(ulong,
89 blockInfo.BlockSize.getQuantity()));
91 // Optional copy/dispose helpers.
92 if (blockInfo.NeedsCopyDispose) {
93 // copy_func_helper_decl
94 elements.push_back(buildCopyHelper(CGM, blockInfo));
97 elements.push_back(buildDisposeHelper(CGM, blockInfo));
100 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
101 std::string typeAtEncoding =
102 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
103 elements.push_back(llvm::ConstantExpr::getBitCast(
104 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
107 if (C.getLangOpts().ObjC1) {
108 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
109 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
111 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
114 elements.push_back(llvm::Constant::getNullValue(i8p));
116 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
118 llvm::GlobalVariable *global =
119 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
120 llvm::GlobalValue::InternalLinkage,
121 init, "__block_descriptor_tmp");
123 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
127 Purely notional variadic template describing the layout of a block.
129 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
130 struct Block_literal {
131 /// Initialized to one of:
132 /// extern void *_NSConcreteStackBlock[];
133 /// extern void *_NSConcreteGlobalBlock[];
135 /// In theory, we could start one off malloc'ed by setting
136 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
138 /// extern void *_NSConcreteMallocBlock[];
139 struct objc_class *isa;
141 /// These are the flags (with corresponding bit number) that the
142 /// compiler is actually supposed to know about.
143 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
144 /// descriptor provides copy and dispose helper functions
145 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
146 /// object with a nontrivial destructor or copy constructor
147 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
149 /// 29. BLOCK_USE_STRET - indicates that the block function
150 /// uses stret, which objc_msgSend needs to know about
151 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
152 /// @encoded signature string
153 /// And we're not supposed to manipulate these:
154 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
155 /// to malloc'ed memory
156 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
157 /// to GC-allocated memory
158 /// Additionally, the bottom 16 bits are a reference count which
159 /// should be zero on the stack.
162 /// Reserved; should be zero-initialized.
165 /// Function pointer generated from block literal.
166 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
168 /// Block description metadata generated from block literal.
169 struct Block_descriptor *block_descriptor;
171 /// Captured values follow.
172 _CapturesTypes captures...;
176 /// The number of fields in a block header.
177 const unsigned BlockHeaderSize = 5;
180 /// A chunk of data that we actually have to capture in the block.
181 struct BlockLayoutChunk {
184 const BlockDecl::Capture *Capture; // null for 'this'
187 BlockLayoutChunk(CharUnits align, CharUnits size,
188 const BlockDecl::Capture *capture,
190 : Alignment(align), Size(size), Capture(capture), Type(type) {}
192 /// Tell the block info that this chunk has the given field index.
193 void setIndex(CGBlockInfo &info, unsigned index) {
195 info.CXXThisIndex = index;
197 info.Captures[Capture->getVariable()]
198 = CGBlockInfo::Capture::makeIndex(index);
202 /// Order by descending alignment.
203 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
204 return left.Alignment > right.Alignment;
208 /// Determines if the given type is safe for constant capture in C++.
209 static bool isSafeForCXXConstantCapture(QualType type) {
210 const RecordType *recordType =
211 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
213 // Only records can be unsafe.
214 if (!recordType) return true;
216 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
218 // Maintain semantics for classes with non-trivial dtors or copy ctors.
219 if (!record->hasTrivialDestructor()) return false;
220 if (!record->hasTrivialCopyConstructor()) return false;
222 // Otherwise, we just have to make sure there aren't any mutable
223 // fields that might have changed since initialization.
224 return !record->hasMutableFields();
227 /// It is illegal to modify a const object after initialization.
228 /// Therefore, if a const object has a constant initializer, we don't
229 /// actually need to keep storage for it in the block; we'll just
230 /// rematerialize it at the start of the block function. This is
231 /// acceptable because we make no promises about address stability of
232 /// captured variables.
233 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
234 CodeGenFunction *CGF,
235 const VarDecl *var) {
236 QualType type = var->getType();
238 // We can only do this if the variable is const.
239 if (!type.isConstQualified()) return 0;
241 // Furthermore, in C++ we have to worry about mutable fields:
242 // C++ [dcl.type.cv]p4:
243 // Except that any class member declared mutable can be
244 // modified, any attempt to modify a const object during its
245 // lifetime results in undefined behavior.
246 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
249 // If the variable doesn't have any initializer (shouldn't this be
250 // invalid?), it's not clear what we should do. Maybe capture as
252 const Expr *init = var->getInit();
255 return CGM.EmitConstantInit(*var, CGF);
258 /// Get the low bit of a nonzero character count. This is the
259 /// alignment of the nth byte if the 0th byte is universally aligned.
260 static CharUnits getLowBit(CharUnits v) {
261 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
264 static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
265 SmallVectorImpl<llvm::Type*> &elementTypes) {
266 ASTContext &C = CGM.getContext();
268 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
269 CharUnits ptrSize, ptrAlign, intSize, intAlign;
270 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
271 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
273 // Are there crazy embedded platforms where this isn't true?
274 assert(intSize <= ptrSize && "layout assumptions horribly violated");
276 CharUnits headerSize = ptrSize;
277 if (2 * intSize < ptrAlign) headerSize += ptrSize;
278 else headerSize += 2 * intSize;
279 headerSize += 2 * ptrSize;
281 info.BlockAlign = ptrAlign;
282 info.BlockSize = headerSize;
284 assert(elementTypes.empty());
285 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
286 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
287 elementTypes.push_back(i8p);
288 elementTypes.push_back(intTy);
289 elementTypes.push_back(intTy);
290 elementTypes.push_back(i8p);
291 elementTypes.push_back(CGM.getBlockDescriptorType());
293 assert(elementTypes.size() == BlockHeaderSize);
296 /// Compute the layout of the given block. Attempts to lay the block
297 /// out with minimal space requirements.
298 static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
300 ASTContext &C = CGM.getContext();
301 const BlockDecl *block = info.getBlockDecl();
303 SmallVector<llvm::Type*, 8> elementTypes;
304 initializeForBlockHeader(CGM, info, elementTypes);
306 if (!block->hasCaptures()) {
308 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
309 info.CanBeGlobal = true;
312 else if (C.getLangOpts().ObjC1 &&
313 CGM.getLangOpts().getGC() == LangOptions::NonGC)
314 info.HasCapturedVariableLayout = true;
316 // Collect the layout chunks.
317 SmallVector<BlockLayoutChunk, 16> layout;
318 layout.reserve(block->capturesCXXThis() +
319 (block->capture_end() - block->capture_begin()));
321 CharUnits maxFieldAlign;
324 if (block->capturesCXXThis()) {
325 const DeclContext *DC = block->getDeclContext();
326 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
329 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
330 thisType = C.getPointerType(C.getRecordType(RD));
332 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
334 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
335 std::pair<CharUnits,CharUnits> tinfo
336 = CGM.getContext().getTypeInfoInChars(thisType);
337 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
342 // Next, all the block captures.
343 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
344 ce = block->capture_end(); ci != ce; ++ci) {
345 const VarDecl *variable = ci->getVariable();
348 // We have to copy/dispose of the __block reference.
349 info.NeedsCopyDispose = true;
351 // Just use void* instead of a pointer to the byref type.
352 QualType byRefPtrTy = C.VoidPtrTy;
354 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
355 std::pair<CharUnits,CharUnits> tinfo
356 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
357 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
359 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
364 // Otherwise, build a layout chunk with the size and alignment of
366 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
367 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
371 // If we have a lifetime qualifier, honor it for capture purposes.
372 // That includes *not* copying it if it's __unsafe_unretained.
373 if (Qualifiers::ObjCLifetime lifetime
374 = variable->getType().getObjCLifetime()) {
376 case Qualifiers::OCL_None: llvm_unreachable("impossible");
377 case Qualifiers::OCL_ExplicitNone:
378 case Qualifiers::OCL_Autoreleasing:
381 case Qualifiers::OCL_Strong:
382 case Qualifiers::OCL_Weak:
383 info.NeedsCopyDispose = true;
386 // Block pointers require copy/dispose. So do Objective-C pointers.
387 } else if (variable->getType()->isObjCRetainableType()) {
388 info.NeedsCopyDispose = true;
390 // So do types that require non-trivial copy construction.
391 } else if (ci->hasCopyExpr()) {
392 info.NeedsCopyDispose = true;
393 info.HasCXXObject = true;
395 // And so do types with destructors.
396 } else if (CGM.getLangOpts().CPlusPlus) {
397 if (const CXXRecordDecl *record =
398 variable->getType()->getAsCXXRecordDecl()) {
399 if (!record->hasTrivialDestructor()) {
400 info.HasCXXObject = true;
401 info.NeedsCopyDispose = true;
406 QualType VT = variable->getType();
407 CharUnits size = C.getTypeSizeInChars(VT);
408 CharUnits align = C.getDeclAlign(variable);
410 maxFieldAlign = std::max(maxFieldAlign, align);
412 llvm::Type *llvmType =
413 CGM.getTypes().ConvertTypeForMem(VT);
415 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
418 // If that was everything, we're done here.
419 if (layout.empty()) {
421 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
422 info.CanBeGlobal = true;
426 // Sort the layout by alignment. We have to use a stable sort here
427 // to get reproducible results. There should probably be an
428 // llvm::array_pod_stable_sort.
429 std::stable_sort(layout.begin(), layout.end());
431 CharUnits &blockSize = info.BlockSize;
432 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
434 // Assuming that the first byte in the header is maximally aligned,
435 // get the alignment of the first byte following the header.
436 CharUnits endAlign = getLowBit(blockSize);
438 // If the end of the header isn't satisfactorily aligned for the
439 // maximum thing, look for things that are okay with the header-end
440 // alignment, and keep appending them until we get something that's
441 // aligned right. This algorithm is only guaranteed optimal if
442 // that condition is satisfied at some point; otherwise we can get
444 // header // next byte has alignment 4
445 // something_with_size_5; // next byte has alignment 1
446 // something_with_alignment_8;
447 // which has 7 bytes of padding, as opposed to the naive solution
448 // which might have less (?).
449 if (endAlign < maxFieldAlign) {
450 SmallVectorImpl<BlockLayoutChunk>::iterator
451 li = layout.begin() + 1, le = layout.end();
453 // Look for something that the header end is already
454 // satisfactorily aligned for.
455 for (; li != le && endAlign < li->Alignment; ++li)
458 // If we found something that's naturally aligned for the end of
459 // the header, keep adding things...
461 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
462 for (; li != le; ++li) {
463 assert(endAlign >= li->Alignment);
465 li->setIndex(info, elementTypes.size());
466 elementTypes.push_back(li->Type);
467 blockSize += li->Size;
468 endAlign = getLowBit(blockSize);
470 // ...until we get to the alignment of the maximum field.
471 if (endAlign >= maxFieldAlign)
475 // Don't re-append everything we just appended.
476 layout.erase(first, li);
480 assert(endAlign == getLowBit(blockSize));
482 // At this point, we just have to add padding if the end align still
483 // isn't aligned right.
484 if (endAlign < maxFieldAlign) {
485 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
486 CharUnits padding = newBlockSize - blockSize;
488 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
489 padding.getQuantity()));
490 blockSize = newBlockSize;
491 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
494 assert(endAlign >= maxFieldAlign);
495 assert(endAlign == getLowBit(blockSize));
497 // Slam everything else on now. This works because they have
498 // strictly decreasing alignment and we expect that size is always a
499 // multiple of alignment.
500 for (SmallVectorImpl<BlockLayoutChunk>::iterator
501 li = layout.begin(), le = layout.end(); li != le; ++li) {
502 assert(endAlign >= li->Alignment);
503 li->setIndex(info, elementTypes.size());
504 elementTypes.push_back(li->Type);
505 blockSize += li->Size;
506 endAlign = getLowBit(blockSize);
510 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
513 /// Enter the scope of a block. This should be run at the entrance to
514 /// a full-expression so that the block's cleanups are pushed at the
515 /// right place in the stack.
516 static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
517 assert(CGF.HaveInsertPoint());
519 // Allocate the block info and place it at the head of the list.
520 CGBlockInfo &blockInfo =
521 *new CGBlockInfo(block, CGF.CurFn->getName());
522 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
523 CGF.FirstBlockInfo = &blockInfo;
525 // Compute information about the layout, etc., of this block,
526 // pushing cleanups as necessary.
527 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
529 // Nothing else to do if it can be global.
530 if (blockInfo.CanBeGlobal) return;
532 // Make the allocation for the block.
534 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
535 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
537 // If there are cleanups to emit, enter them (but inactive).
538 if (!blockInfo.NeedsCopyDispose) return;
540 // Walk through the captures (in order) and find the ones not
541 // captured by constant.
542 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
543 ce = block->capture_end(); ci != ce; ++ci) {
544 // Ignore __block captures; there's nothing special in the
545 // on-stack block that we need to do for them.
546 if (ci->isByRef()) continue;
548 // Ignore variables that are constant-captured.
549 const VarDecl *variable = ci->getVariable();
550 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
551 if (capture.isConstant()) continue;
553 // Ignore objects that aren't destructed.
554 QualType::DestructionKind dtorKind =
555 variable->getType().isDestructedType();
556 if (dtorKind == QualType::DK_none) continue;
558 CodeGenFunction::Destroyer *destroyer;
560 // Block captures count as local values and have imprecise semantics.
561 // They also can't be arrays, so need to worry about that.
562 if (dtorKind == QualType::DK_objc_strong_lifetime) {
563 destroyer = CodeGenFunction::destroyARCStrongImprecise;
565 destroyer = CGF.getDestroyer(dtorKind);
568 // GEP down to the address.
569 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
572 // We can use that GEP as the dominating IP.
573 if (!blockInfo.DominatingIP)
574 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
576 CleanupKind cleanupKind = InactiveNormalCleanup;
577 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
578 if (useArrayEHCleanup)
579 cleanupKind = InactiveNormalAndEHCleanup;
581 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
582 destroyer, useArrayEHCleanup);
584 // Remember where that cleanup was.
585 capture.setCleanup(CGF.EHStack.stable_begin());
589 /// Enter a full-expression with a non-trivial number of objects to
590 /// clean up. This is in this file because, at the moment, the only
591 /// kind of cleanup object is a BlockDecl*.
592 void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
593 assert(E->getNumObjects() != 0);
594 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
595 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
596 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
597 enterBlockScope(*this, *i);
601 /// Find the layout for the given block in a linked list and remove it.
602 static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
603 const BlockDecl *block) {
605 assert(head && *head);
606 CGBlockInfo *cur = *head;
608 // If this is the block we're looking for, splice it out of the list.
609 if (cur->getBlockDecl() == block) {
610 *head = cur->NextBlockInfo;
614 head = &cur->NextBlockInfo;
618 /// Destroy a chain of block layouts.
619 void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
620 assert(head && "destroying an empty chain");
622 CGBlockInfo *cur = head;
623 head = cur->NextBlockInfo;
628 /// Emit a block literal expression in the current function.
629 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
630 // If the block has no captures, we won't have a pre-computed
632 if (!blockExpr->getBlockDecl()->hasCaptures()) {
633 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
634 computeBlockInfo(CGM, this, blockInfo);
635 blockInfo.BlockExpression = blockExpr;
636 return EmitBlockLiteral(blockInfo);
639 // Find the block info for this block and take ownership of it.
640 OwningPtr<CGBlockInfo> blockInfo;
641 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
642 blockExpr->getBlockDecl()));
644 blockInfo->BlockExpression = blockExpr;
645 return EmitBlockLiteral(*blockInfo);
648 llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
649 // Using the computed layout, generate the actual block function.
650 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
651 llvm::Constant *blockFn
652 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
653 CurFuncDecl, LocalDeclMap,
655 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
657 // If there is nothing to capture, we can emit this as a global block.
658 if (blockInfo.CanBeGlobal)
659 return buildGlobalBlock(CGM, blockInfo, blockFn);
661 // Otherwise, we have to emit this as a local block.
663 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
664 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
666 // Build the block descriptor.
667 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
669 llvm::AllocaInst *blockAddr = blockInfo.Address;
670 assert(blockAddr && "block has no address!");
672 // Compute the initial on-stack block flags.
673 BlockFlags flags = BLOCK_HAS_SIGNATURE;
674 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
675 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
676 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
677 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
679 // Initialize the block literal.
680 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
681 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
682 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
683 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
684 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
685 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
687 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
688 "block.descriptor"));
690 // Finally, capture all the values into the block.
691 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
694 if (blockDecl->capturesCXXThis()) {
695 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
696 blockInfo.CXXThisIndex,
697 "block.captured-this.addr");
698 Builder.CreateStore(LoadCXXThis(), addr);
701 // Next, captured variables.
702 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
703 ce = blockDecl->capture_end(); ci != ce; ++ci) {
704 const VarDecl *variable = ci->getVariable();
705 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
707 // Ignore constant captures.
708 if (capture.isConstant()) continue;
710 QualType type = variable->getType();
712 // This will be a [[type]]*, except that a byref entry will just be
714 llvm::Value *blockField =
715 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
718 // Compute the address of the thing we're going to move into the
721 if (BlockInfo && ci->isNested()) {
722 // We need to use the capture from the enclosing block.
723 const CGBlockInfo::Capture &enclosingCapture =
724 BlockInfo->getCapture(variable);
726 // This is a [[type]]*, except that a byref entry wil just be an i8**.
727 src = Builder.CreateStructGEP(LoadBlockStruct(),
728 enclosingCapture.getIndex(),
729 "block.capture.addr");
730 } else if (blockDecl->isConversionFromLambda()) {
731 // The lambda capture in a lambda's conversion-to-block-pointer is
732 // special; we'll simply emit it directly.
735 // This is a [[type]]*.
736 src = LocalDeclMap[variable];
739 // For byrefs, we just write the pointer to the byref struct into
740 // the block field. There's no need to chase the forwarding
741 // pointer at this point, since we're building something that will
742 // live a shorter life than the stack byref anyway.
744 // Get a void* that points to the byref struct.
746 src = Builder.CreateLoad(src, "byref.capture");
748 src = Builder.CreateBitCast(src, VoidPtrTy);
750 // Write that void* into the capture field.
751 Builder.CreateStore(src, blockField);
753 // If we have a copy constructor, evaluate that into the block field.
754 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
755 if (blockDecl->isConversionFromLambda()) {
756 // If we have a lambda conversion, emit the expression
757 // directly into the block instead.
758 CharUnits Align = getContext().getTypeAlignInChars(type);
760 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
761 AggValueSlot::IsDestructed,
762 AggValueSlot::DoesNotNeedGCBarriers,
763 AggValueSlot::IsNotAliased);
764 EmitAggExpr(copyExpr, Slot);
766 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
769 // If it's a reference variable, copy the reference into the block field.
770 } else if (type->isReferenceType()) {
771 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
773 // Otherwise, fake up a POD copy into the block field.
775 // Fake up a new variable so that EmitScalarInit doesn't think
776 // we're referring to the variable in its own initializer.
777 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
780 // We use one of these or the other depending on whether the
781 // reference is nested.
782 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
783 /*refersToEnclosing*/ ci->isNested(), type,
784 VK_LValue, SourceLocation());
786 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
787 &declRef, VK_RValue);
788 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
789 MakeAddrLValue(blockField, type,
790 getContext().getDeclAlign(variable)),
791 /*captured by init*/ false);
794 // Activate the cleanup if layout pushed one.
795 if (!ci->isByRef()) {
796 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
797 if (cleanup.isValid())
798 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
802 // Cast to the converted block-pointer type, which happens (somewhat
803 // unfortunately) to be a pointer to function type.
804 llvm::Value *result =
805 Builder.CreateBitCast(blockAddr,
806 ConvertType(blockInfo.getBlockExpr()->getType()));
812 llvm::Type *CodeGenModule::getBlockDescriptorType() {
813 if (BlockDescriptorType)
814 return BlockDescriptorType;
816 llvm::Type *UnsignedLongTy =
817 getTypes().ConvertType(getContext().UnsignedLongTy);
819 // struct __block_descriptor {
820 // unsigned long reserved;
821 // unsigned long block_size;
823 // // later, the following will be added
826 // void (*copyHelper)();
827 // void (*copyHelper)();
828 // } helpers; // !!! optional
830 // const char *signature; // the block signature
831 // const char *layout; // reserved
833 BlockDescriptorType =
834 llvm::StructType::create("struct.__block_descriptor",
835 UnsignedLongTy, UnsignedLongTy, NULL);
837 // Now form a pointer to that.
838 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
839 return BlockDescriptorType;
842 llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
843 if (GenericBlockLiteralType)
844 return GenericBlockLiteralType;
846 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
848 // struct __block_literal_generic {
852 // void (*__invoke)(void *);
853 // struct __block_descriptor *__descriptor;
855 GenericBlockLiteralType =
856 llvm::StructType::create("struct.__block_literal_generic",
857 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
858 BlockDescPtrTy, NULL);
860 return GenericBlockLiteralType;
864 RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
865 ReturnValueSlot ReturnValue) {
866 const BlockPointerType *BPT =
867 E->getCallee()->getType()->getAs<BlockPointerType>();
869 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
871 // Get a pointer to the generic block literal.
872 llvm::Type *BlockLiteralTy =
873 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
875 // Bitcast the callee to a block literal.
876 llvm::Value *BlockLiteral =
877 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
879 // Get the function pointer from the literal.
880 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
882 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
884 // Add the block literal.
886 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
888 QualType FnType = BPT->getPointeeType();
890 // And the rest of the arguments.
891 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
892 E->arg_begin(), E->arg_end());
894 // Load the function.
895 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
897 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
898 const CGFunctionInfo &FnInfo =
899 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
901 // Cast the function pointer to the right type.
902 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
904 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
905 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
907 // And call the block.
908 return EmitCall(FnInfo, Func, ReturnValue, Args);
911 llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
913 assert(BlockInfo && "evaluating block ref without block information?");
914 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
916 // Handle constant captures.
917 if (capture.isConstant()) return LocalDeclMap[variable];
920 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
921 "block.capture.addr");
924 // addr should be a void** right now. Load, then cast the result
927 addr = Builder.CreateLoad(addr);
928 llvm::PointerType *byrefPointerType
929 = llvm::PointerType::get(BuildByRefType(variable), 0);
930 addr = Builder.CreateBitCast(addr, byrefPointerType,
933 // Follow the forwarding pointer.
934 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
935 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
937 // Cast back to byref* and GEP over to the actual object.
938 addr = Builder.CreateBitCast(addr, byrefPointerType);
939 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
940 variable->getNameAsString());
943 if (variable->getType()->isReferenceType())
944 addr = Builder.CreateLoad(addr, "ref.tmp");
950 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
952 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
953 blockInfo.BlockExpression = blockExpr;
955 // Compute information about the layout, etc., of this block.
956 computeBlockInfo(*this, 0, blockInfo);
958 // Using that metadata, generate the actual block function.
959 llvm::Constant *blockFn;
961 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
962 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
967 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
969 return buildGlobalBlock(*this, blockInfo, blockFn);
972 static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
973 const CGBlockInfo &blockInfo,
974 llvm::Constant *blockFn) {
975 assert(blockInfo.CanBeGlobal);
977 // Generate the constants for the block literal initializer.
978 llvm::Constant *fields[BlockHeaderSize];
981 fields[0] = CGM.getNSConcreteGlobalBlock();
984 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
985 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
987 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
990 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
996 fields[4] = buildBlockDescriptor(CGM, blockInfo);
998 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
1000 llvm::GlobalVariable *literal =
1001 new llvm::GlobalVariable(CGM.getModule(),
1004 llvm::GlobalVariable::InternalLinkage,
1006 "__block_literal_global");
1007 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1009 // Return a constant of the appropriately-casted type.
1010 llvm::Type *requiredType =
1011 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1012 return llvm::ConstantExpr::getBitCast(literal, requiredType);
1016 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1017 const CGBlockInfo &blockInfo,
1018 const Decl *outerFnDecl,
1019 const DeclMapTy &ldm,
1020 bool IsLambdaConversionToBlock) {
1021 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1023 // Check if we should generate debug info for this block function.
1024 maybeInitializeDebugInfo();
1027 BlockInfo = &blockInfo;
1029 // Arrange for local static and local extern declarations to appear
1030 // to be local to this function as well, in case they're directly
1031 // referenced in a block.
1032 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1033 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1034 if (var && !var->hasLocalStorage())
1035 LocalDeclMap[var] = i->second;
1038 // Begin building the function declaration.
1040 // Build the argument list.
1041 FunctionArgList args;
1043 // The first argument is the block pointer. Just take it as a void*
1044 // and cast it later.
1045 QualType selfTy = getContext().VoidPtrTy;
1046 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
1048 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1049 SourceLocation(), II, selfTy);
1050 args.push_back(&selfDecl);
1052 // Now add the rest of the parameters.
1053 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1054 e = blockDecl->param_end(); i != e; ++i)
1057 // Create the function declaration.
1058 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
1059 const CGFunctionInfo &fnInfo =
1060 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1061 fnType->getExtInfo(),
1062 fnType->isVariadic());
1063 if (CGM.ReturnTypeUsesSRet(fnInfo))
1064 blockInfo.UsesStret = true;
1066 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
1069 CGM.getBlockMangledName(GD, name, blockDecl);
1070 llvm::Function *fn =
1071 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1072 name.getString(), &CGM.getModule());
1073 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
1075 // Begin generating the function.
1076 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
1077 blockInfo.getBlockExpr()->getBody()->getLocStart());
1078 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
1080 // Okay. Undo some of what StartFunction did.
1082 // Pull the 'self' reference out of the local decl map.
1083 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1084 LocalDeclMap.erase(&selfDecl);
1085 BlockPointer = Builder.CreateBitCast(blockAddr,
1086 blockInfo.StructureType->getPointerTo(),
1089 // If we have a C++ 'this' reference, go ahead and force it into
1091 if (blockDecl->capturesCXXThis()) {
1092 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1093 blockInfo.CXXThisIndex,
1094 "block.captured-this");
1095 CXXThisValue = Builder.CreateLoad(addr, "this");
1098 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1100 if (const ObjCMethodDecl *method
1101 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1102 const VarDecl *self = method->getSelfDecl();
1104 // There might not be a capture for 'self', but if there is...
1105 if (blockInfo.Captures.count(self)) {
1106 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1107 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1109 "block.captured-self");
1110 LocalDeclMap[self] = selfAddr;
1114 // Also force all the constant captures.
1115 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1116 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1117 const VarDecl *variable = ci->getVariable();
1118 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1119 if (!capture.isConstant()) continue;
1121 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1123 llvm::AllocaInst *alloca =
1124 CreateMemTemp(variable->getType(), "block.captured-const");
1125 alloca->setAlignment(align);
1127 Builder.CreateStore(capture.getConstant(), alloca, align);
1129 LocalDeclMap[variable] = alloca;
1132 // Save a spot to insert the debug information for all the DeclRefExprs.
1133 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1134 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1137 if (IsLambdaConversionToBlock)
1138 EmitLambdaBlockInvokeBody();
1140 EmitStmt(blockDecl->getBody());
1142 // Remember where we were...
1143 llvm::BasicBlock *resume = Builder.GetInsertBlock();
1145 // Go back to the entry.
1147 Builder.SetInsertPoint(entry, entry_ptr);
1149 // Emit debug information for all the DeclRefExprs.
1150 // FIXME: also for 'this'
1151 if (CGDebugInfo *DI = getDebugInfo()) {
1152 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1153 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1154 const VarDecl *variable = ci->getVariable();
1155 DI->EmitLocation(Builder, variable->getLocation());
1157 if (CGM.getCodeGenOpts().getDebugInfo()
1158 >= CodeGenOptions::LimitedDebugInfo) {
1159 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1160 if (capture.isConstant()) {
1161 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1166 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1167 Builder, blockInfo);
1172 // And resume where we left off.
1174 Builder.ClearInsertionPoint();
1176 Builder.SetInsertPoint(resume);
1178 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
1184 notes.push_back(HelperInfo());
1185 HelperInfo ¬e = notes.back();
1186 note.index = capture.getIndex();
1187 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1188 note.cxxbar_import = ci->getCopyExpr();
1190 if (ci->isByRef()) {
1191 note.flag = BLOCK_FIELD_IS_BYREF;
1192 if (type.isObjCGCWeak())
1193 note.flag |= BLOCK_FIELD_IS_WEAK;
1194 } else if (type->isBlockPointerType()) {
1195 note.flag = BLOCK_FIELD_IS_BLOCK;
1197 note.flag = BLOCK_FIELD_IS_OBJECT;
1204 CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1205 ASTContext &C = getContext();
1207 FunctionArgList args;
1208 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1209 args.push_back(&dstDecl);
1210 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1211 args.push_back(&srcDecl);
1213 const CGFunctionInfo &FI =
1214 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1215 FunctionType::ExtInfo(),
1216 /*variadic*/ false);
1218 // FIXME: it would be nice if these were mergeable with things with
1219 // identical semantics.
1220 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1222 llvm::Function *Fn =
1223 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1224 "__copy_helper_block_", &CGM.getModule());
1227 = &CGM.getContext().Idents.get("__copy_helper_block_");
1229 // Check if we should generate debug info for this block helper function.
1230 maybeInitializeDebugInfo();
1232 FunctionDecl *FD = FunctionDecl::Create(C,
1233 C.getTranslationUnitDecl(),
1235 SourceLocation(), II, C.VoidTy, 0,
1240 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1242 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1244 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1245 src = Builder.CreateLoad(src);
1246 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
1248 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
1249 dst = Builder.CreateLoad(dst);
1250 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
1252 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1254 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1255 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1256 const VarDecl *variable = ci->getVariable();
1257 QualType type = variable->getType();
1259 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1260 if (capture.isConstant()) continue;
1262 const Expr *copyExpr = ci->getCopyExpr();
1263 BlockFieldFlags flags;
1265 bool useARCWeakCopy = false;
1266 bool useARCStrongCopy = false;
1269 assert(!ci->isByRef());
1270 // don't bother computing flags
1272 } else if (ci->isByRef()) {
1273 flags = BLOCK_FIELD_IS_BYREF;
1274 if (type.isObjCGCWeak())
1275 flags |= BLOCK_FIELD_IS_WEAK;
1277 } else if (type->isObjCRetainableType()) {
1278 flags = BLOCK_FIELD_IS_OBJECT;
1279 bool isBlockPointer = type->isBlockPointerType();
1281 flags = BLOCK_FIELD_IS_BLOCK;
1283 // Special rules for ARC captures:
1284 if (getLangOpts().ObjCAutoRefCount) {
1285 Qualifiers qs = type.getQualifiers();
1287 // We need to register __weak direct captures with the runtime.
1288 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1289 useARCWeakCopy = true;
1291 // We need to retain the copied value for __strong direct captures.
1292 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1293 // If it's a block pointer, we have to copy the block and
1294 // assign that to the destination pointer, so we might as
1295 // well use _Block_object_assign. Otherwise we can avoid that.
1296 if (!isBlockPointer)
1297 useARCStrongCopy = true;
1299 // Otherwise the memcpy is fine.
1304 // Non-ARC captures of retainable pointers are strong and
1305 // therefore require a call to _Block_object_assign.
1313 unsigned index = capture.getIndex();
1314 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1315 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
1317 // If there's an explicit copy expression, we do that.
1319 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1320 } else if (useARCWeakCopy) {
1321 EmitARCCopyWeak(dstField, srcField);
1323 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1324 if (useARCStrongCopy) {
1325 // At -O0, store null into the destination field (so that the
1326 // storeStrong doesn't over-release) and then call storeStrong.
1327 // This is a workaround to not having an initStrong call.
1328 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1329 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1330 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1331 Builder.CreateStore(null, dstField);
1332 EmitARCStoreStrongCall(dstField, srcValue, true);
1334 // With optimization enabled, take advantage of the fact that
1335 // the blocks runtime guarantees a memcpy of the block data, and
1336 // just emit a retain of the src field.
1338 EmitARCRetainNonBlock(srcValue);
1340 // We don't need this anymore, so kill it. It's not quite
1341 // worth the annoyance to avoid creating it in the first place.
1342 cast<llvm::Instruction>(dstField)->eraseFromParent();
1345 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1346 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1347 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1348 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1355 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1359 CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1360 ASTContext &C = getContext();
1362 FunctionArgList args;
1363 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1364 args.push_back(&srcDecl);
1366 const CGFunctionInfo &FI =
1367 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1368 FunctionType::ExtInfo(),
1369 /*variadic*/ false);
1371 // FIXME: We'd like to put these into a mergable by content, with
1372 // internal linkage.
1373 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
1375 llvm::Function *Fn =
1376 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1377 "__destroy_helper_block_", &CGM.getModule());
1379 // Check if we should generate debug info for this block destroy function.
1380 maybeInitializeDebugInfo();
1383 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1385 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1387 SourceLocation(), II, C.VoidTy, 0,
1391 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
1393 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
1395 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
1396 src = Builder.CreateLoad(src);
1397 src = Builder.CreateBitCast(src, structPtrTy, "block");
1399 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1401 CodeGenFunction::RunCleanupsScope cleanups(*this);
1403 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1404 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1405 const VarDecl *variable = ci->getVariable();
1406 QualType type = variable->getType();
1408 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1409 if (capture.isConstant()) continue;
1411 BlockFieldFlags flags;
1412 const CXXDestructorDecl *dtor = 0;
1414 bool useARCWeakDestroy = false;
1415 bool useARCStrongDestroy = false;
1417 if (ci->isByRef()) {
1418 flags = BLOCK_FIELD_IS_BYREF;
1419 if (type.isObjCGCWeak())
1420 flags |= BLOCK_FIELD_IS_WEAK;
1421 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1422 if (record->hasTrivialDestructor())
1424 dtor = record->getDestructor();
1425 } else if (type->isObjCRetainableType()) {
1426 flags = BLOCK_FIELD_IS_OBJECT;
1427 if (type->isBlockPointerType())
1428 flags = BLOCK_FIELD_IS_BLOCK;
1430 // Special rules for ARC captures.
1431 if (getLangOpts().ObjCAutoRefCount) {
1432 Qualifiers qs = type.getQualifiers();
1434 // Don't generate special dispose logic for a captured object
1435 // unless it's __strong or __weak.
1436 if (!qs.hasStrongOrWeakObjCLifetime())
1439 // Support __weak direct captures.
1440 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1441 useARCWeakDestroy = true;
1443 // Tools really want us to use objc_storeStrong here.
1445 useARCStrongDestroy = true;
1451 unsigned index = capture.getIndex();
1452 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1454 // If there's an explicit copy expression, we do that.
1456 PushDestructorCleanup(dtor, srcField);
1458 // If this is a __weak capture, emit the release directly.
1459 } else if (useARCWeakDestroy) {
1460 EmitARCDestroyWeak(srcField);
1462 // Destroy strong objects with a call if requested.
1463 } else if (useARCStrongDestroy) {
1464 EmitARCDestroyStrong(srcField, /*precise*/ false);
1466 // Otherwise we call _Block_object_dispose. It wouldn't be too
1467 // hard to just emit this as a cleanup if we wanted to make sure
1468 // that things were done in reverse.
1470 llvm::Value *value = Builder.CreateLoad(srcField);
1471 value = Builder.CreateBitCast(value, VoidPtrTy);
1472 BuildBlockRelease(value, flags);
1476 cleanups.ForceCleanup();
1480 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
1485 /// Emits the copy/dispose helper functions for a __block object of id type.
1486 class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1487 BlockFieldFlags Flags;
1490 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1491 : ByrefHelpers(alignment), Flags(flags) {}
1493 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1494 llvm::Value *srcField) {
1495 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1497 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1498 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1500 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1502 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1503 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1504 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1507 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1508 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1509 llvm::Value *value = CGF.Builder.CreateLoad(field);
1511 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1514 void profileImpl(llvm::FoldingSetNodeID &id) const {
1515 id.AddInteger(Flags.getBitMask());
1519 /// Emits the copy/dispose helpers for an ARC __block __weak variable.
1520 class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1522 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1524 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1525 llvm::Value *srcField) {
1526 CGF.EmitARCMoveWeak(destField, srcField);
1529 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1530 CGF.EmitARCDestroyWeak(field);
1533 void profileImpl(llvm::FoldingSetNodeID &id) const {
1534 // 0 is distinguishable from all pointers and byref flags
1539 /// Emits the copy/dispose helpers for an ARC __block __strong variable
1540 /// that's not of block-pointer type.
1541 class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1543 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1545 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1546 llvm::Value *srcField) {
1547 // Do a "move" by copying the value and then zeroing out the old
1550 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1551 value->setAlignment(Alignment.getQuantity());
1554 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1556 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1557 store->setAlignment(Alignment.getQuantity());
1559 store = CGF.Builder.CreateStore(null, srcField);
1560 store->setAlignment(Alignment.getQuantity());
1563 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1564 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
1567 void profileImpl(llvm::FoldingSetNodeID &id) const {
1568 // 1 is distinguishable from all pointers and byref flags
1573 /// Emits the copy/dispose helpers for an ARC __block __strong
1574 /// variable that's of block-pointer type.
1575 class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1577 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1579 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1580 llvm::Value *srcField) {
1581 // Do the copy with objc_retainBlock; that's all that
1582 // _Block_object_assign would do anyway, and we'd have to pass the
1583 // right arguments to make sure it doesn't get no-op'ed.
1584 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1585 oldValue->setAlignment(Alignment.getQuantity());
1587 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1589 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1590 store->setAlignment(Alignment.getQuantity());
1593 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1594 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
1597 void profileImpl(llvm::FoldingSetNodeID &id) const {
1598 // 2 is distinguishable from all pointers and byref flags
1603 /// Emits the copy/dispose helpers for a __block variable with a
1604 /// nontrivial copy constructor or destructor.
1605 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1607 const Expr *CopyExpr;
1610 CXXByrefHelpers(CharUnits alignment, QualType type,
1611 const Expr *copyExpr)
1612 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1614 bool needsCopy() const { return CopyExpr != 0; }
1615 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1616 llvm::Value *srcField) {
1617 if (!CopyExpr) return;
1618 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1621 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1622 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1623 CGF.PushDestructorCleanup(VarType, field);
1624 CGF.PopCleanupBlocks(cleanupDepth);
1627 void profileImpl(llvm::FoldingSetNodeID &id) const {
1628 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1631 } // end anonymous namespace
1633 static llvm::Constant *
1634 generateByrefCopyHelper(CodeGenFunction &CGF,
1635 llvm::StructType &byrefType,
1636 CodeGenModule::ByrefHelpers &byrefInfo) {
1637 ASTContext &Context = CGF.getContext();
1639 QualType R = Context.VoidTy;
1641 FunctionArgList args;
1642 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
1643 args.push_back(&dst);
1645 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1646 args.push_back(&src);
1648 const CGFunctionInfo &FI =
1649 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1650 FunctionType::ExtInfo(),
1651 /*variadic*/ false);
1653 CodeGenTypes &Types = CGF.CGM.getTypes();
1654 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1656 // FIXME: We'd like to put these into a mergable by content, with
1657 // internal linkage.
1658 llvm::Function *Fn =
1659 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1660 "__Block_byref_object_copy_", &CGF.CGM.getModule());
1663 = &Context.Idents.get("__Block_byref_object_copy_");
1665 FunctionDecl *FD = FunctionDecl::Create(Context,
1666 Context.getTranslationUnitDecl(),
1668 SourceLocation(), II, R, 0,
1673 // Initialize debug info if necessary.
1674 CGF.maybeInitializeDebugInfo();
1675 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1677 if (byrefInfo.needsCopy()) {
1678 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
1681 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1682 destField = CGF.Builder.CreateLoad(destField);
1683 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1684 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
1687 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1688 srcField = CGF.Builder.CreateLoad(srcField);
1689 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1690 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1692 byrefInfo.emitCopy(CGF, destField, srcField);
1695 CGF.FinishFunction();
1697 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1700 /// Build the copy helper for a __block variable.
1701 static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1702 llvm::StructType &byrefType,
1703 CodeGenModule::ByrefHelpers &info) {
1704 CodeGenFunction CGF(CGM);
1705 return generateByrefCopyHelper(CGF, byrefType, info);
1708 /// Generate code for a __block variable's dispose helper.
1709 static llvm::Constant *
1710 generateByrefDisposeHelper(CodeGenFunction &CGF,
1711 llvm::StructType &byrefType,
1712 CodeGenModule::ByrefHelpers &byrefInfo) {
1713 ASTContext &Context = CGF.getContext();
1714 QualType R = Context.VoidTy;
1716 FunctionArgList args;
1717 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
1718 args.push_back(&src);
1720 const CGFunctionInfo &FI =
1721 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1722 FunctionType::ExtInfo(),
1723 /*variadic*/ false);
1725 CodeGenTypes &Types = CGF.CGM.getTypes();
1726 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
1728 // FIXME: We'd like to put these into a mergable by content, with
1729 // internal linkage.
1730 llvm::Function *Fn =
1731 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1732 "__Block_byref_object_dispose_",
1733 &CGF.CGM.getModule());
1736 = &Context.Idents.get("__Block_byref_object_dispose_");
1738 FunctionDecl *FD = FunctionDecl::Create(Context,
1739 Context.getTranslationUnitDecl(),
1741 SourceLocation(), II, R, 0,
1745 // Initialize debug info if necessary.
1746 CGF.maybeInitializeDebugInfo();
1747 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
1749 if (byrefInfo.needsDispose()) {
1750 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1751 V = CGF.Builder.CreateLoad(V);
1752 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1753 V = CGF.Builder.CreateStructGEP(V, 6, "x");
1755 byrefInfo.emitDispose(CGF, V);
1758 CGF.FinishFunction();
1760 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
1763 /// Build the dispose helper for a __block variable.
1764 static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1765 llvm::StructType &byrefType,
1766 CodeGenModule::ByrefHelpers &info) {
1767 CodeGenFunction CGF(CGM);
1768 return generateByrefDisposeHelper(CGF, byrefType, info);
1772 template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1773 llvm::StructType &byrefTy,
1775 // Increase the field's alignment to be at least pointer alignment,
1776 // since the layout of the byref struct will guarantee at least that.
1777 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1778 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1780 llvm::FoldingSetNodeID id;
1781 byrefInfo.Profile(id);
1784 CodeGenModule::ByrefHelpers *node
1785 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1786 if (node) return static_cast<T*>(node);
1788 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1789 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1791 T *copy = new (CGM.getContext()) T(byrefInfo);
1792 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1796 CodeGenModule::ByrefHelpers *
1797 CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
1798 const AutoVarEmission &emission) {
1799 const VarDecl &var = *emission.Variable;
1800 QualType type = var.getType();
1802 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1803 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1804 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1806 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1807 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1810 // Otherwise, if we don't have a retainable type, there's nothing to do.
1811 // that the runtime does extra copies.
1812 if (!type->isObjCRetainableType()) return 0;
1814 Qualifiers qs = type.getQualifiers();
1816 // If we have lifetime, that dominates.
1817 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1818 assert(getLangOpts().ObjCAutoRefCount);
1821 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1823 // These are just bits as far as the runtime is concerned.
1824 case Qualifiers::OCL_ExplicitNone:
1825 case Qualifiers::OCL_Autoreleasing:
1828 // Tell the runtime that this is ARC __weak, called by the
1830 case Qualifiers::OCL_Weak: {
1831 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1832 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1835 // ARC __strong __block variables need to be retained.
1836 case Qualifiers::OCL_Strong:
1837 // Block pointers need to be copied, and there's no direct
1838 // transfer possible.
1839 if (type->isBlockPointerType()) {
1840 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
1841 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1843 // Otherwise, we transfer ownership of the retain from the stack
1846 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1847 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1850 llvm_unreachable("fell out of lifetime switch!");
1853 BlockFieldFlags flags;
1854 if (type->isBlockPointerType()) {
1855 flags |= BLOCK_FIELD_IS_BLOCK;
1856 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1857 type->isObjCObjectPointerType()) {
1858 flags |= BLOCK_FIELD_IS_OBJECT;
1863 if (type.isObjCGCWeak())
1864 flags |= BLOCK_FIELD_IS_WEAK;
1866 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1867 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1870 unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1871 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1873 return ByRefValueInfo.find(VD)->second.second;
1876 llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1878 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1879 Loc = Builder.CreateLoad(Loc);
1880 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1881 V->getNameAsString());
1885 /// BuildByRefType - This routine changes a __block variable declared as T x
1890 /// void *__forwarding;
1891 /// int32_t __flags;
1893 /// void *__copy_helper; // only if needed
1894 /// void *__destroy_helper; // only if needed
1895 /// char padding[X]; // only if needed
1899 llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1900 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1904 QualType Ty = D->getType();
1906 SmallVector<llvm::Type *, 8> types;
1908 llvm::StructType *ByRefType =
1909 llvm::StructType::create(getLLVMContext(),
1910 "struct.__block_byref_" + D->getNameAsString());
1913 types.push_back(Int8PtrTy);
1915 // void *__forwarding;
1916 types.push_back(llvm::PointerType::getUnqual(ByRefType));
1919 types.push_back(Int32Ty);
1922 types.push_back(Int32Ty);
1924 bool HasCopyAndDispose =
1925 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
1926 if (HasCopyAndDispose) {
1927 /// void *__copy_helper;
1928 types.push_back(Int8PtrTy);
1930 /// void *__destroy_helper;
1931 types.push_back(Int8PtrTy);
1934 bool Packed = false;
1935 CharUnits Align = getContext().getDeclAlign(D);
1936 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1937 // We have to insert padding.
1939 // The struct above has 2 32-bit integers.
1940 unsigned CurrentOffsetInBytes = 4 * 2;
1942 // And either 2 or 4 pointers.
1943 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1944 CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
1946 // Align the offset.
1947 unsigned AlignedOffsetInBytes =
1948 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1950 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1951 if (NumPaddingBytes > 0) {
1952 llvm::Type *Ty = Int8Ty;
1953 // FIXME: We need a sema error for alignment larger than the minimum of
1954 // the maximal stack alignment and the alignment of malloc on the system.
1955 if (NumPaddingBytes > 1)
1956 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1958 types.push_back(Ty);
1960 // We want a packed struct.
1966 types.push_back(ConvertTypeForMem(Ty));
1968 ByRefType->setBody(types, Packed);
1970 Info.first = ByRefType;
1972 Info.second = types.size() - 1;
1977 /// Initialize the structural components of a __block variable, i.e.
1978 /// everything but the actual object.
1979 void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
1980 // Find the address of the local.
1981 llvm::Value *addr = emission.Address;
1983 // That's an alloca of the byref structure type.
1984 llvm::StructType *byrefType = cast<llvm::StructType>(
1985 cast<llvm::PointerType>(addr->getType())->getElementType());
1987 // Build the byref helpers if necessary. This is null if we don't need any.
1988 CodeGenModule::ByrefHelpers *helpers =
1989 buildByrefHelpers(*byrefType, emission);
1991 const VarDecl &D = *emission.Variable;
1992 QualType type = D.getType();
1996 // Initialize the 'isa', which is just 0 or 1.
1998 if (type.isObjCGCWeak())
2000 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2001 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2003 // Store the address of the variable into its own forwarding pointer.
2004 Builder.CreateStore(addr,
2005 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2008 // c) the flags field is set to either 0 if no helper functions are
2009 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
2011 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
2012 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2013 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2015 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2016 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
2017 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2020 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
2021 Builder.CreateStore(helpers->CopyHelper, copy_helper);
2023 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
2024 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
2028 void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
2029 llvm::Value *F = CGM.getBlockObjectDispose();
2031 V = Builder.CreateBitCast(V, Int8PtrTy);
2032 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
2033 Builder.CreateCall2(F, V, N);
2037 struct CallBlockRelease : EHScopeStack::Cleanup {
2039 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2041 void Emit(CodeGenFunction &CGF, Flags flags) {
2042 // Should we be passing FIELD_IS_WEAK here?
2043 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2048 /// Enter a cleanup to destroy a __block variable. Note that this
2049 /// cleanup should be a no-op if the variable hasn't left the stack
2050 /// yet; if a cleanup is required for the variable itself, that needs
2051 /// to be done externally.
2052 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2053 // We don't enter this cleanup if we're in pure-GC mode.
2054 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
2057 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2060 /// Adjust the declaration of something from the blocks API.
2061 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2062 llvm::Constant *C) {
2063 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
2065 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2066 if (GV->isDeclaration() &&
2067 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2068 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2071 llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2072 if (BlockObjectDispose)
2073 return BlockObjectDispose;
2075 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2076 llvm::FunctionType *fty
2077 = llvm::FunctionType::get(VoidTy, args, false);
2078 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2079 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2080 return BlockObjectDispose;
2083 llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2084 if (BlockObjectAssign)
2085 return BlockObjectAssign;
2087 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2088 llvm::FunctionType *fty
2089 = llvm::FunctionType::get(VoidTy, args, false);
2090 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2091 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2092 return BlockObjectAssign;
2095 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2096 if (NSConcreteGlobalBlock)
2097 return NSConcreteGlobalBlock;
2099 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2100 Int8PtrTy->getPointerTo(), 0);
2101 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2102 return NSConcreteGlobalBlock;
2105 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2106 if (NSConcreteStackBlock)
2107 return NSConcreteStackBlock;
2109 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2110 Int8PtrTy->getPointerTo(), 0);
2111 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2112 return NSConcreteStackBlock;