blob: f11d528e13d9fdf2250253c6e0799be594ef6e0a [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall6b5a61b2011-02-07 10:33:21 +000028CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall64cd2322011-03-09 08:39:33 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000031
32 // Skip asm prefix, if any.
33 if (Name && Name[0] == '\01')
34 ++Name;
35}
36
John McCallf0c11f72011-03-31 08:03:29 +000037// Anchor the vtable to this translation unit.
38CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
39
John McCall6b5a61b2011-02-07 10:33:21 +000040/// Build the given block as a global block.
41static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
42 const CGBlockInfo &blockInfo,
43 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000044
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the helper function to copy a block.
46static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo) {
48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
49}
50
51/// Build the helper function to dipose of a block.
52static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
55}
56
57/// Build the block descriptor constant for a block.
58static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 ASTContext &C = CGM.getContext();
61
62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
64
65 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000068 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000069
70 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000071 // FIXME: What is the right way to say this doesn't fit? We should give
72 // a user diagnostic in that case. Better fix would be to change the
73 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000074 elements.push_back(llvm::ConstantInt::get(ulong,
75 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000076
John McCall6b5a61b2011-02-07 10:33:21 +000077 // Optional copy/dispose helpers.
78 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000079 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000084 }
85
John McCall6b5a61b2011-02-07 10:33:21 +000086 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
87 std::string typeAtEncoding =
88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
89 elements.push_back(llvm::ConstantExpr::getBitCast(
90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // GC layout.
93 if (C.getLangOptions().ObjC1)
94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
95 else
96 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000097
John McCall6b5a61b2011-02-07 10:33:21 +000098 llvm::Constant *init =
99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
100 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
169 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
173 const llvm::Type *type)
174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
218 const VarDecl *var) {
219 QualType type = var->getType();
220
221 // We can only do this if the variable is const.
222 if (!type.isConstQualified()) return 0;
223
John McCall461c9c12011-02-08 03:07:00 +0000224 // Furthermore, in C++ we have to worry about mutable fields:
225 // C++ [dcl.type.cv]p4:
226 // Except that any class member declared mutable can be
227 // modified, any attempt to modify a const object during its
228 // lifetime results in undefined behavior.
229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000230 return 0;
231
232 // If the variable doesn't have any initializer (shouldn't this be
233 // invalid?), it's not clear what we should do. Maybe capture as
234 // zero?
235 const Expr *init = var->getInit();
236 if (!init) return 0;
237
238 return CGM.EmitConstantExpr(init, var->getType());
239}
240
241/// Get the low bit of a nonzero character count. This is the
242/// alignment of the nth byte if the 0th byte is universally aligned.
243static CharUnits getLowBit(CharUnits v) {
244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
245}
246
247static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
John McCall0774cb82011-05-15 01:53:33 +0000248 llvm::SmallVectorImpl<const llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000249 ASTContext &C = CGM.getContext();
250
251 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
252 CharUnits ptrSize, ptrAlign, intSize, intAlign;
253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
255
256 // Are there crazy embedded platforms where this isn't true?
257 assert(intSize <= ptrSize && "layout assumptions horribly violated");
258
259 CharUnits headerSize = ptrSize;
260 if (2 * intSize < ptrAlign) headerSize += ptrSize;
261 else headerSize += 2 * intSize;
262 headerSize += 2 * ptrSize;
263
264 info.BlockAlign = ptrAlign;
265 info.BlockSize = headerSize;
266
267 assert(elementTypes.empty());
268 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
269 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
270 elementTypes.push_back(i8p);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(i8p);
274 elementTypes.push_back(CGM.getBlockDescriptorType());
275
276 assert(elementTypes.size() == BlockHeaderSize);
277}
278
279/// Compute the layout of the given block. Attempts to lay the block
280/// out with minimal space requirements.
281static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
282 ASTContext &C = CGM.getContext();
283 const BlockDecl *block = info.getBlockDecl();
284
John McCall0774cb82011-05-15 01:53:33 +0000285 llvm::SmallVector<const llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000286 initializeForBlockHeader(CGM, info, elementTypes);
287
288 if (!block->hasCaptures()) {
289 info.StructureType =
290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
291 info.CanBeGlobal = true;
292 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
Mike Stump00470a12009-03-05 08:32:30 +0000294
John McCall6b5a61b2011-02-07 10:33:21 +0000295 // Collect the layout chunks.
296 llvm::SmallVector<BlockLayoutChunk, 16> layout;
297 layout.reserve(block->capturesCXXThis() +
298 (block->capture_end() - block->capture_begin()));
299
300 CharUnits maxFieldAlign;
301
302 // First, 'this'.
303 if (block->capturesCXXThis()) {
304 const DeclContext *DC = block->getDeclContext();
305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
306 ;
307 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
308
309 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
310 std::pair<CharUnits,CharUnits> tinfo
311 = CGM.getContext().getTypeInfoInChars(thisType);
312 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
313
314 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
315 }
316
317 // Next, all the block captures.
318 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
319 ce = block->capture_end(); ci != ce; ++ci) {
320 const VarDecl *variable = ci->getVariable();
321
322 if (ci->isByRef()) {
323 // We have to copy/dispose of the __block reference.
324 info.NeedsCopyDispose = true;
325
John McCall6b5a61b2011-02-07 10:33:21 +0000326 // Just use void* instead of a pointer to the byref type.
327 QualType byRefPtrTy = C.VoidPtrTy;
328
329 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
330 std::pair<CharUnits,CharUnits> tinfo
331 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
332 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
333
334 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
335 &*ci, llvmType));
336 continue;
337 }
338
339 // Otherwise, build a layout chunk with the size and alignment of
340 // the declaration.
341 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
342 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
343 continue;
344 }
345
346 // Block pointers require copy/dispose.
347 if (variable->getType()->isBlockPointerType()) {
348 info.NeedsCopyDispose = true;
349
350 // So do Objective-C pointers.
351 } else if (variable->getType()->isObjCObjectPointerType() ||
352 C.isObjCNSObjectType(variable->getType())) {
353 info.NeedsCopyDispose = true;
354
355 // So do types that require non-trivial copy construction.
356 } else if (ci->hasCopyExpr()) {
357 info.NeedsCopyDispose = true;
358 info.HasCXXObject = true;
359
360 // And so do types with destructors.
361 } else if (CGM.getLangOptions().CPlusPlus) {
362 if (const CXXRecordDecl *record =
363 variable->getType()->getAsCXXRecordDecl()) {
364 if (!record->hasTrivialDestructor()) {
365 info.HasCXXObject = true;
366 info.NeedsCopyDispose = true;
367 }
368 }
369 }
370
371 CharUnits size = C.getTypeSizeInChars(variable->getType());
372 CharUnits align = C.getDeclAlign(variable);
373 maxFieldAlign = std::max(maxFieldAlign, align);
374
375 const llvm::Type *llvmType =
376 CGM.getTypes().ConvertTypeForMem(variable->getType());
377
378 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
379 }
380
381 // If that was everything, we're done here.
382 if (layout.empty()) {
383 info.StructureType =
384 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
385 info.CanBeGlobal = true;
386 return;
387 }
388
389 // Sort the layout by alignment. We have to use a stable sort here
390 // to get reproducible results. There should probably be an
391 // llvm::array_pod_stable_sort.
392 std::stable_sort(layout.begin(), layout.end());
393
394 CharUnits &blockSize = info.BlockSize;
395 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
396
397 // Assuming that the first byte in the header is maximally aligned,
398 // get the alignment of the first byte following the header.
399 CharUnits endAlign = getLowBit(blockSize);
400
401 // If the end of the header isn't satisfactorily aligned for the
402 // maximum thing, look for things that are okay with the header-end
403 // alignment, and keep appending them until we get something that's
404 // aligned right. This algorithm is only guaranteed optimal if
405 // that condition is satisfied at some point; otherwise we can get
406 // things like:
407 // header // next byte has alignment 4
408 // something_with_size_5; // next byte has alignment 1
409 // something_with_alignment_8;
410 // which has 7 bytes of padding, as opposed to the naive solution
411 // which might have less (?).
412 if (endAlign < maxFieldAlign) {
413 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
414 li = layout.begin() + 1, le = layout.end();
415
416 // Look for something that the header end is already
417 // satisfactorily aligned for.
418 for (; li != le && endAlign < li->Alignment; ++li)
419 ;
420
421 // If we found something that's naturally aligned for the end of
422 // the header, keep adding things...
423 if (li != le) {
424 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
425 for (; li != le; ++li) {
426 assert(endAlign >= li->Alignment);
427
428 li->setIndex(info, elementTypes.size());
429 elementTypes.push_back(li->Type);
430 blockSize += li->Size;
431 endAlign = getLowBit(blockSize);
432
433 // ...until we get to the alignment of the maximum field.
434 if (endAlign >= maxFieldAlign)
435 break;
436 }
437
438 // Don't re-append everything we just appended.
439 layout.erase(first, li);
440 }
441 }
442
443 // At this point, we just have to add padding if the end align still
444 // isn't aligned right.
445 if (endAlign < maxFieldAlign) {
446 CharUnits padding = maxFieldAlign - endAlign;
447
John McCall5936e332011-02-15 09:22:45 +0000448 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
449 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000450 blockSize += padding;
451
452 endAlign = getLowBit(blockSize);
453 assert(endAlign >= maxFieldAlign);
454 }
455
456 // Slam everything else on now. This works because they have
457 // strictly decreasing alignment and we expect that size is always a
458 // multiple of alignment.
459 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
460 li = layout.begin(), le = layout.end(); li != le; ++li) {
461 assert(endAlign >= li->Alignment);
462 li->setIndex(info, elementTypes.size());
463 elementTypes.push_back(li->Type);
464 blockSize += li->Size;
465 endAlign = getLowBit(blockSize);
466 }
467
468 info.StructureType =
469 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
470}
471
472/// Emit a block literal expression in the current function.
473llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
474 std::string Name = CurFn->getName();
475 CGBlockInfo blockInfo(blockExpr, Name.c_str());
476
477 // Compute information about the layout, etc., of this block.
478 computeBlockInfo(CGM, blockInfo);
479
480 // Using that metadata, generate the actual block function.
481 llvm::Constant *blockFn
482 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
483 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000484 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000485
486 // If there is nothing to capture, we can emit this as a global block.
487 if (blockInfo.CanBeGlobal)
488 return buildGlobalBlock(CGM, blockInfo, blockFn);
489
490 // Otherwise, we have to emit this as a local block.
491
492 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000493 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000494
495 // Build the block descriptor.
496 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
497
498 const llvm::Type *intTy = ConvertType(getContext().IntTy);
499
500 llvm::AllocaInst *blockAddr =
501 CreateTempAlloca(blockInfo.StructureType, "block");
502 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
503
504 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000505 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000506 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
507 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000508 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000509
510 // Initialize the block literal.
511 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000512 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000513 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
514 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
515 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
516 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
517 "block.invoke"));
518 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
519 "block.descriptor"));
520
521 // Finally, capture all the values into the block.
522 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
523
524 // First, 'this'.
525 if (blockDecl->capturesCXXThis()) {
526 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
527 blockInfo.CXXThisIndex,
528 "block.captured-this.addr");
529 Builder.CreateStore(LoadCXXThis(), addr);
530 }
531
532 // Next, captured variables.
533 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
534 ce = blockDecl->capture_end(); ci != ce; ++ci) {
535 const VarDecl *variable = ci->getVariable();
536 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
537
538 // Ignore constant captures.
539 if (capture.isConstant()) continue;
540
541 QualType type = variable->getType();
542
543 // This will be a [[type]]*, except that a byref entry will just be
544 // an i8**.
545 llvm::Value *blockField =
546 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
547 "block.captured");
548
549 // Compute the address of the thing we're going to move into the
550 // block literal.
551 llvm::Value *src;
552 if (ci->isNested()) {
553 // We need to use the capture from the enclosing block.
554 const CGBlockInfo::Capture &enclosingCapture =
555 BlockInfo->getCapture(variable);
556
557 // This is a [[type]]*, except that a byref entry wil just be an i8**.
558 src = Builder.CreateStructGEP(LoadBlockStruct(),
559 enclosingCapture.getIndex(),
560 "block.capture.addr");
561 } else {
562 // This is a [[type]]*.
563 src = LocalDeclMap[variable];
564 }
565
566 // For byrefs, we just write the pointer to the byref struct into
567 // the block field. There's no need to chase the forwarding
568 // pointer at this point, since we're building something that will
569 // live a shorter life than the stack byref anyway.
570 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000571 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000572 if (ci->isNested())
573 src = Builder.CreateLoad(src, "byref.capture");
574 else
John McCall5936e332011-02-15 09:22:45 +0000575 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000576
John McCall5936e332011-02-15 09:22:45 +0000577 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000578 Builder.CreateStore(src, blockField);
579
580 // If we have a copy constructor, evaluate that into the block field.
581 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
582 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
583
584 // If it's a reference variable, copy the reference into the block field.
585 } else if (type->isReferenceType()) {
586 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
587
588 // Otherwise, fake up a POD copy into the block field.
589 } else {
John McCallbb699b02011-02-07 18:37:40 +0000590 // We use one of these or the other depending on whether the
591 // reference is nested.
592 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
593 SourceLocation());
594 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
595 VK_LValue, SourceLocation(), /*byref*/ false);
596
597 Expr *declRef =
598 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
599
John McCall6b5a61b2011-02-07 10:33:21 +0000600 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000601 declRef, VK_RValue);
John McCalldf045202011-03-08 09:38:48 +0000602 EmitExprAsInit(&l2r, variable, blockField,
603 getContext().getDeclAlign(variable),
604 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000605 }
606
607 // Push a destructor if necessary. The semantics for when this
608 // actually gets run are really obscure.
609 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
610 PushDestructorCleanup(type, blockField);
611 }
612
613 // Cast to the converted block-pointer type, which happens (somewhat
614 // unfortunately) to be a pointer to function type.
615 llvm::Value *result =
616 Builder.CreateBitCast(blockAddr,
617 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000618
John McCall6b5a61b2011-02-07 10:33:21 +0000619 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000620}
621
622
John McCalld16c2cf2011-02-08 08:22:06 +0000623const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000624 if (BlockDescriptorType)
625 return BlockDescriptorType;
626
Mike Stumpa5448542009-02-13 15:32:32 +0000627 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000628 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000629
Mike Stumpab695142009-02-13 15:16:56 +0000630 // struct __block_descriptor {
631 // unsigned long reserved;
632 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000633 //
634 // // later, the following will be added
635 //
636 // struct {
637 // void (*copyHelper)();
638 // void (*copyHelper)();
639 // } helpers; // !!! optional
640 //
641 // const char *signature; // the block signature
642 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000643 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000644 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
645 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000646 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000647 NULL);
648
649 getModule().addTypeName("struct.__block_descriptor",
650 BlockDescriptorType);
651
John McCall6b5a61b2011-02-07 10:33:21 +0000652 // Now form a pointer to that.
653 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000654 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000655}
656
John McCalld16c2cf2011-02-08 08:22:06 +0000657const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000658 if (GenericBlockLiteralType)
659 return GenericBlockLiteralType;
660
John McCall6b5a61b2011-02-07 10:33:21 +0000661 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000662
Mike Stump9b8a7972009-02-13 15:25:34 +0000663 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000664 // void *__isa;
665 // int __flags;
666 // int __reserved;
667 // void (*__invoke)(void *);
668 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000669 // };
John McCall5936e332011-02-15 09:22:45 +0000670 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
671 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000672 IntTy,
673 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000674 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000675 BlockDescPtrTy,
676 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000677
Mike Stump9b8a7972009-02-13 15:25:34 +0000678 getModule().addTypeName("struct.__block_literal_generic",
679 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000680
Mike Stump9b8a7972009-02-13 15:25:34 +0000681 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000682}
683
Mike Stumpbd65cac2009-02-19 01:01:04 +0000684
Anders Carlssona1736c02009-12-24 21:13:40 +0000685RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
686 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000687 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000688 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000689
Anders Carlssonacfde802009-02-12 00:39:25 +0000690 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
691
692 // Get a pointer to the generic block literal.
693 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000694 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000695
696 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000697 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000698 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
699
700 // Get the function pointer from the literal.
701 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000702
John McCall5936e332011-02-15 09:22:45 +0000703 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000704
Anders Carlssonacfde802009-02-12 00:39:25 +0000705 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000706 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000707 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000708
Anders Carlsson782f3972009-04-08 23:13:16 +0000709 QualType FnType = BPT->getPointeeType();
710
Anders Carlssonacfde802009-02-12 00:39:25 +0000711 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000712 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000713 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000714
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000715 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000716 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000717
John McCall64cd2322011-03-09 08:39:33 +0000718 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000719 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000720
Mike Stump1eb44332009-09-09 15:08:12 +0000721 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000722 CGM.getTypes().getFunctionInfo(ResultType, Args,
723 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000725 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000726 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000727 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Owen Anderson96e0fc72009-07-29 22:16:19 +0000729 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000730 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Anders Carlssonacfde802009-02-12 00:39:25 +0000732 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000733 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000734}
Anders Carlssond5cab542009-02-12 17:55:02 +0000735
John McCall6b5a61b2011-02-07 10:33:21 +0000736llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
737 bool isByRef) {
738 assert(BlockInfo && "evaluating block ref without block information?");
739 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000740
John McCall6b5a61b2011-02-07 10:33:21 +0000741 // Handle constant captures.
742 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000743
John McCall6b5a61b2011-02-07 10:33:21 +0000744 llvm::Value *addr =
745 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
746 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000747
John McCall6b5a61b2011-02-07 10:33:21 +0000748 if (isByRef) {
749 // addr should be a void** right now. Load, then cast the result
750 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000751
John McCall6b5a61b2011-02-07 10:33:21 +0000752 addr = Builder.CreateLoad(addr);
753 const llvm::PointerType *byrefPointerType
754 = llvm::PointerType::get(BuildByRefType(variable), 0);
755 addr = Builder.CreateBitCast(addr, byrefPointerType,
756 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000757
John McCall6b5a61b2011-02-07 10:33:21 +0000758 // Follow the forwarding pointer.
759 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
760 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000761
John McCall6b5a61b2011-02-07 10:33:21 +0000762 // Cast back to byref* and GEP over to the actual object.
763 addr = Builder.CreateBitCast(addr, byrefPointerType);
764 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
765 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000766 }
767
John McCall6b5a61b2011-02-07 10:33:21 +0000768 if (variable->getType()->isReferenceType())
769 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000770
John McCall6b5a61b2011-02-07 10:33:21 +0000771 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000772}
773
Mike Stump67a64482009-02-14 22:16:35 +0000774llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000775CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000776 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000777 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000778
John McCall6b5a61b2011-02-07 10:33:21 +0000779 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000780 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000781
John McCall6b5a61b2011-02-07 10:33:21 +0000782 // Using that metadata, generate the actual block function.
783 llvm::Constant *blockFn;
784 {
785 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000786 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
787 blockInfo,
788 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000789 }
John McCall5936e332011-02-15 09:22:45 +0000790 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000791
John McCalld16c2cf2011-02-08 08:22:06 +0000792 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000793}
794
John McCall6b5a61b2011-02-07 10:33:21 +0000795static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
796 const CGBlockInfo &blockInfo,
797 llvm::Constant *blockFn) {
798 assert(blockInfo.CanBeGlobal);
799
800 // Generate the constants for the block literal initializer.
801 llvm::Constant *fields[BlockHeaderSize];
802
803 // isa
804 fields[0] = CGM.getNSConcreteGlobalBlock();
805
806 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000807 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
808 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
809
John McCall5936e332011-02-15 09:22:45 +0000810 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000811
812 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000813 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000814
815 // Function
816 fields[3] = blockFn;
817
818 // Descriptor
819 fields[4] = buildBlockDescriptor(CGM, blockInfo);
820
821 llvm::Constant *init =
822 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
823 /*packed*/ false);
824
825 llvm::GlobalVariable *literal =
826 new llvm::GlobalVariable(CGM.getModule(),
827 init->getType(),
828 /*constant*/ true,
829 llvm::GlobalVariable::InternalLinkage,
830 init,
831 "__block_literal_global");
832 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
833
834 // Return a constant of the appropriately-casted type.
835 const llvm::Type *requiredType =
836 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
837 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000838}
839
Mike Stump00470a12009-03-05 08:32:30 +0000840llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000841CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
842 const CGBlockInfo &blockInfo,
843 const Decl *outerFnDecl,
844 const DeclMapTy &ldm) {
845 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000846
Devang Patel6d1155b2011-03-07 21:53:18 +0000847 // Check if we should generate debug info for this block function.
848 if (CGM.getModuleDebugInfo())
849 DebugInfo = CGM.getModuleDebugInfo();
850
John McCall6b5a61b2011-02-07 10:33:21 +0000851 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Mike Stump7f28a9c2009-03-13 23:34:28 +0000853 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000854 // to be local to this function as well, in case they're directly
855 // referenced in a block.
856 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
857 const VarDecl *var = dyn_cast<VarDecl>(i->first);
858 if (var && !var->hasLocalStorage())
859 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000860 }
861
John McCall6b5a61b2011-02-07 10:33:21 +0000862 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000863
John McCall6b5a61b2011-02-07 10:33:21 +0000864 // Build the argument list.
865 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000866
John McCall6b5a61b2011-02-07 10:33:21 +0000867 // The first argument is the block pointer. Just take it as a void*
868 // and cast it later.
869 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000870 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000871
John McCall8178df32011-02-22 22:38:33 +0000872 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
873 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000874 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000875
John McCall6b5a61b2011-02-07 10:33:21 +0000876 // Now add the rest of the parameters.
877 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
878 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000879 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000880
John McCall6b5a61b2011-02-07 10:33:21 +0000881 // Create the function declaration.
882 const FunctionProtoType *fnType =
883 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
884 const CGFunctionInfo &fnInfo =
885 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
886 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000887 if (CGM.ReturnTypeUsesSRet(fnInfo))
888 blockInfo.UsesStret = true;
889
John McCall6b5a61b2011-02-07 10:33:21 +0000890 const llvm::FunctionType *fnLLVMType =
891 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000892
John McCall6b5a61b2011-02-07 10:33:21 +0000893 MangleBuffer name;
894 CGM.getBlockMangledName(GD, name, blockDecl);
895 llvm::Function *fn =
896 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
897 name.getString(), &CGM.getModule());
898 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000899
John McCall6b5a61b2011-02-07 10:33:21 +0000900 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000901 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000902 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000903 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000904
John McCall8178df32011-02-22 22:38:33 +0000905 // Okay. Undo some of what StartFunction did.
906
907 // Pull the 'self' reference out of the local decl map.
908 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
909 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000910 BlockPointer = Builder.CreateBitCast(blockAddr,
911 blockInfo.StructureType->getPointerTo(),
912 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000913
John McCallea1471e2010-05-20 01:18:31 +0000914 // If we have a C++ 'this' reference, go ahead and force it into
915 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000916 if (blockDecl->capturesCXXThis()) {
917 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
918 blockInfo.CXXThisIndex,
919 "block.captured-this");
920 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000921 }
922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
924 // appease it.
925 if (const ObjCMethodDecl *method
926 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
927 const VarDecl *self = method->getSelfDecl();
928
929 // There might not be a capture for 'self', but if there is...
930 if (blockInfo.Captures.count(self)) {
931 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
932 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
933 capture.getIndex(),
934 "block.captured-self");
935 LocalDeclMap[self] = selfAddr;
936 }
937 }
938
939 // Also force all the constant captures.
940 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
941 ce = blockDecl->capture_end(); ci != ce; ++ci) {
942 const VarDecl *variable = ci->getVariable();
943 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
944 if (!capture.isConstant()) continue;
945
946 unsigned align = getContext().getDeclAlign(variable).getQuantity();
947
948 llvm::AllocaInst *alloca =
949 CreateMemTemp(variable->getType(), "block.captured-const");
950 alloca->setAlignment(align);
951
952 Builder.CreateStore(capture.getConstant(), alloca, align);
953
954 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000955 }
956
Mike Stumpb289b3f2009-10-01 22:29:41 +0000957 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
958 llvm::BasicBlock *entry = Builder.GetInsertBlock();
959 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
960 --entry_ptr;
961
John McCall6b5a61b2011-02-07 10:33:21 +0000962 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000963
Mike Stumpde8c5c72009-10-01 00:27:30 +0000964 // Remember where we were...
965 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000966
Mike Stumpde8c5c72009-10-01 00:27:30 +0000967 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000968 ++entry_ptr;
969 Builder.SetInsertPoint(entry, entry_ptr);
970
John McCall6b5a61b2011-02-07 10:33:21 +0000971 // Emit debug information for all the BlockDeclRefDecls.
972 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000973 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000974 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
975 ce = blockDecl->capture_end(); ci != ce; ++ci) {
976 const VarDecl *variable = ci->getVariable();
977 DI->setLocation(variable->getLocation());
978
979 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
980 if (capture.isConstant()) {
981 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
982 Builder);
983 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +0000984 }
John McCall6b5a61b2011-02-07 10:33:21 +0000985
John McCall8178df32011-02-22 22:38:33 +0000986 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +0000987 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000988 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000989 }
John McCall6b5a61b2011-02-07 10:33:21 +0000990
Mike Stumpde8c5c72009-10-01 00:27:30 +0000991 // And resume where we left off.
992 if (resume == 0)
993 Builder.ClearInsertionPoint();
994 else
995 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000996
John McCall6b5a61b2011-02-07 10:33:21 +0000997 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000998
John McCall6b5a61b2011-02-07 10:33:21 +0000999 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001000}
Mike Stumpa99038c2009-02-28 09:07:16 +00001001
John McCall6b5a61b2011-02-07 10:33:21 +00001002/*
1003 notes.push_back(HelperInfo());
1004 HelperInfo &note = notes.back();
1005 note.index = capture.getIndex();
1006 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1007 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001008
John McCall6b5a61b2011-02-07 10:33:21 +00001009 if (ci->isByRef()) {
1010 note.flag = BLOCK_FIELD_IS_BYREF;
1011 if (type.isObjCGCWeak())
1012 note.flag |= BLOCK_FIELD_IS_WEAK;
1013 } else if (type->isBlockPointerType()) {
1014 note.flag = BLOCK_FIELD_IS_BLOCK;
1015 } else {
1016 note.flag = BLOCK_FIELD_IS_OBJECT;
1017 }
1018 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001019
Mike Stump00470a12009-03-05 08:32:30 +00001020
Mike Stumpa99038c2009-02-28 09:07:16 +00001021
Mike Stumpdab514f2009-03-04 03:23:46 +00001022
Mike Stumpa4f668f2009-03-06 01:33:24 +00001023
John McCall6b5a61b2011-02-07 10:33:21 +00001024llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001025CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001026 ASTContext &C = getContext();
1027
1028 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001029 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1030 args.push_back(&dstDecl);
1031 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1032 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Mike Stumpa4f668f2009-03-06 01:33:24 +00001034 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001035 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001036
John McCall6b5a61b2011-02-07 10:33:21 +00001037 // FIXME: it would be nice if these were mergeable with things with
1038 // identical semantics.
1039 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001040
1041 llvm::Function *Fn =
1042 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001043 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001044
1045 IdentifierInfo *II
1046 = &CGM.getContext().Idents.get("__copy_helper_block_");
1047
Devang Patel58dc5ca2011-05-02 20:37:08 +00001048 // Check if we should generate debug info for this block helper function.
1049 if (CGM.getModuleDebugInfo())
1050 DebugInfo = CGM.getModuleDebugInfo();
1051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 FunctionDecl *FD = FunctionDecl::Create(C,
1053 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001054 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001055 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001056 SC_Static,
1057 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001058 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001059 true);
John McCalld26bc762011-03-09 04:27:21 +00001060 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001061
John McCall6b5a61b2011-02-07 10:33:21 +00001062 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001063
John McCalld26bc762011-03-09 04:27:21 +00001064 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001065 src = Builder.CreateLoad(src);
1066 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001067
John McCalld26bc762011-03-09 04:27:21 +00001068 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001069 dst = Builder.CreateLoad(dst);
1070 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001071
John McCall6b5a61b2011-02-07 10:33:21 +00001072 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001073
John McCall6b5a61b2011-02-07 10:33:21 +00001074 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1075 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1076 const VarDecl *variable = ci->getVariable();
1077 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001078
John McCall6b5a61b2011-02-07 10:33:21 +00001079 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1080 if (capture.isConstant()) continue;
1081
1082 const Expr *copyExpr = ci->getCopyExpr();
1083 unsigned flags = 0;
1084
1085 if (copyExpr) {
1086 assert(!ci->isByRef());
1087 // don't bother computing flags
1088 } else if (ci->isByRef()) {
1089 flags = BLOCK_FIELD_IS_BYREF;
1090 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1091 } else if (type->isBlockPointerType()) {
1092 flags = BLOCK_FIELD_IS_BLOCK;
1093 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1094 flags = BLOCK_FIELD_IS_OBJECT;
1095 }
1096
1097 if (!copyExpr && !flags) continue;
1098
1099 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001100 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1101 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001102
1103 // If there's an explicit copy expression, we do that.
1104 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001105 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001106 } else {
1107 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001108 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1109 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001110 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001111 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001112 }
1113 }
1114
John McCalld16c2cf2011-02-08 08:22:06 +00001115 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001116
John McCall5936e332011-02-15 09:22:45 +00001117 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001118}
1119
John McCall6b5a61b2011-02-07 10:33:21 +00001120llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001121CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001122 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001123
John McCall6b5a61b2011-02-07 10:33:21 +00001124 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001125 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1126 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Mike Stumpa4f668f2009-03-06 01:33:24 +00001128 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001129 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001130
Mike Stump3899a7f2009-06-05 23:26:36 +00001131 // FIXME: We'd like to put these into a mergable by content, with
1132 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001133 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001134
1135 llvm::Function *Fn =
1136 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001137 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001138
Devang Patel58dc5ca2011-05-02 20:37:08 +00001139 // Check if we should generate debug info for this block destroy function.
1140 if (CGM.getModuleDebugInfo())
1141 DebugInfo = CGM.getModuleDebugInfo();
1142
Mike Stumpa4f668f2009-03-06 01:33:24 +00001143 IdentifierInfo *II
1144 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1145
John McCall6b5a61b2011-02-07 10:33:21 +00001146 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001147 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001148 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001149 SC_Static,
1150 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001151 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001152 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001153
John McCall6b5a61b2011-02-07 10:33:21 +00001154 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001155
John McCalld26bc762011-03-09 04:27:21 +00001156 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001157 src = Builder.CreateLoad(src);
1158 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001159
John McCall6b5a61b2011-02-07 10:33:21 +00001160 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1161
John McCalld16c2cf2011-02-08 08:22:06 +00001162 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001163
1164 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1165 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1166 const VarDecl *variable = ci->getVariable();
1167 QualType type = variable->getType();
1168
1169 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1170 if (capture.isConstant()) continue;
1171
John McCalld16c2cf2011-02-08 08:22:06 +00001172 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001173 const CXXDestructorDecl *dtor = 0;
1174
1175 if (ci->isByRef()) {
1176 flags = BLOCK_FIELD_IS_BYREF;
1177 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1178 } else if (type->isBlockPointerType()) {
1179 flags = BLOCK_FIELD_IS_BLOCK;
1180 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1181 flags = BLOCK_FIELD_IS_OBJECT;
1182 } else if (C.getLangOptions().CPlusPlus) {
1183 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1184 if (!record->hasTrivialDestructor())
1185 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001186 }
John McCall6b5a61b2011-02-07 10:33:21 +00001187
John McCalld16c2cf2011-02-08 08:22:06 +00001188 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001189
1190 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001191 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001192
1193 // If there's an explicit copy expression, we do that.
1194 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001195 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001196
1197 // Otherwise we call _Block_object_dispose. It wouldn't be too
1198 // hard to just emit this as a cleanup if we wanted to make sure
1199 // that things were done in reverse.
1200 } else {
1201 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001202 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001203 BuildBlockRelease(value, flags);
1204 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001205 }
1206
John McCall6b5a61b2011-02-07 10:33:21 +00001207 cleanups.ForceCleanup();
1208
John McCalld16c2cf2011-02-08 08:22:06 +00001209 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001210
John McCall5936e332011-02-15 09:22:45 +00001211 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001212}
1213
John McCallf0c11f72011-03-31 08:03:29 +00001214namespace {
1215
1216/// Emits the copy/dispose helper functions for a __block object of id type.
1217class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1218 BlockFieldFlags Flags;
1219
1220public:
1221 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1222 : ByrefHelpers(alignment), Flags(flags) {}
1223
John McCall36170192011-03-31 09:19:20 +00001224 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1225 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001226 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1227
1228 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1229 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1230
1231 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1232
1233 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1234 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1235 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1236 }
1237
1238 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1239 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1240 llvm::Value *value = CGF.Builder.CreateLoad(field);
1241
1242 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1243 }
1244
1245 void profileImpl(llvm::FoldingSetNodeID &id) const {
1246 id.AddInteger(Flags.getBitMask());
1247 }
1248};
1249
1250/// Emits the copy/dispose helpers for a __block variable with a
1251/// nontrivial copy constructor or destructor.
1252class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1253 QualType VarType;
1254 const Expr *CopyExpr;
1255
1256public:
1257 CXXByrefHelpers(CharUnits alignment, QualType type,
1258 const Expr *copyExpr)
1259 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1260
1261 bool needsCopy() const { return CopyExpr != 0; }
1262 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1263 llvm::Value *srcField) {
1264 if (!CopyExpr) return;
1265 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1266 }
1267
1268 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1269 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1270 CGF.PushDestructorCleanup(VarType, field);
1271 CGF.PopCleanupBlocks(cleanupDepth);
1272 }
1273
1274 void profileImpl(llvm::FoldingSetNodeID &id) const {
1275 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1276 }
1277};
1278} // end anonymous namespace
1279
1280static llvm::Constant *
1281generateByrefCopyHelper(CodeGenFunction &CGF,
1282 const llvm::StructType &byrefType,
1283 CodeGenModule::ByrefHelpers &byrefInfo) {
1284 ASTContext &Context = CGF.getContext();
1285
1286 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001287
John McCalld26bc762011-03-09 04:27:21 +00001288 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001289 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001290 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001291
John McCallf0c11f72011-03-31 08:03:29 +00001292 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001293 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Mike Stump45031c02009-03-06 02:29:21 +00001295 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001296 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001297
John McCallf0c11f72011-03-31 08:03:29 +00001298 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001299 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1300
Mike Stump3899a7f2009-06-05 23:26:36 +00001301 // FIXME: We'd like to put these into a mergable by content, with
1302 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001303 llvm::Function *Fn =
1304 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001305 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001306
1307 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001308 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001309
John McCallf0c11f72011-03-31 08:03:29 +00001310 FunctionDecl *FD = FunctionDecl::Create(Context,
1311 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001312 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001313 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001314 SC_Static,
1315 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001316 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001317 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001318
John McCallf0c11f72011-03-31 08:03:29 +00001319 if (byrefInfo.needsCopy()) {
1320 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001321
John McCallf0c11f72011-03-31 08:03:29 +00001322 // dst->x
1323 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1324 destField = CGF.Builder.CreateLoad(destField);
1325 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1326 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001327
John McCallf0c11f72011-03-31 08:03:29 +00001328 // src->x
1329 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1330 srcField = CGF.Builder.CreateLoad(srcField);
1331 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1332 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1333
1334 byrefInfo.emitCopy(CGF, destField, srcField);
1335 }
1336
1337 CGF.FinishFunction();
1338
1339 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001340}
1341
John McCallf0c11f72011-03-31 08:03:29 +00001342/// Build the copy helper for a __block variable.
1343static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1344 const llvm::StructType &byrefType,
1345 CodeGenModule::ByrefHelpers &info) {
1346 CodeGenFunction CGF(CGM);
1347 return generateByrefCopyHelper(CGF, byrefType, info);
1348}
1349
1350/// Generate code for a __block variable's dispose helper.
1351static llvm::Constant *
1352generateByrefDisposeHelper(CodeGenFunction &CGF,
1353 const llvm::StructType &byrefType,
1354 CodeGenModule::ByrefHelpers &byrefInfo) {
1355 ASTContext &Context = CGF.getContext();
1356 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001357
John McCalld26bc762011-03-09 04:27:21 +00001358 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001359 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001360 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Mike Stump45031c02009-03-06 02:29:21 +00001362 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001363 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001364
John McCallf0c11f72011-03-31 08:03:29 +00001365 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001366 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1367
Mike Stump3899a7f2009-06-05 23:26:36 +00001368 // FIXME: We'd like to put these into a mergable by content, with
1369 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001370 llvm::Function *Fn =
1371 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001372 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001373 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001374
1375 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001376 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001377
John McCallf0c11f72011-03-31 08:03:29 +00001378 FunctionDecl *FD = FunctionDecl::Create(Context,
1379 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001380 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001381 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001382 SC_Static,
1383 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001384 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001385 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001386
John McCallf0c11f72011-03-31 08:03:29 +00001387 if (byrefInfo.needsDispose()) {
1388 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1389 V = CGF.Builder.CreateLoad(V);
1390 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1391 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001392
John McCallf0c11f72011-03-31 08:03:29 +00001393 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001394 }
Mike Stump45031c02009-03-06 02:29:21 +00001395
John McCallf0c11f72011-03-31 08:03:29 +00001396 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001397
John McCallf0c11f72011-03-31 08:03:29 +00001398 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001399}
1400
John McCallf0c11f72011-03-31 08:03:29 +00001401/// Build the dispose helper for a __block variable.
1402static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1403 const llvm::StructType &byrefType,
1404 CodeGenModule::ByrefHelpers &info) {
1405 CodeGenFunction CGF(CGM);
1406 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001407}
1408
John McCallf0c11f72011-03-31 08:03:29 +00001409///
1410template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1411 const llvm::StructType &byrefTy,
1412 T &byrefInfo) {
1413 // Increase the field's alignment to be at least pointer alignment,
1414 // since the layout of the byref struct will guarantee at least that.
1415 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1416 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1417
1418 llvm::FoldingSetNodeID id;
1419 byrefInfo.Profile(id);
1420
1421 void *insertPos;
1422 CodeGenModule::ByrefHelpers *node
1423 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1424 if (node) return static_cast<T*>(node);
1425
1426 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1427 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1428
1429 T *copy = new (CGM.getContext()) T(byrefInfo);
1430 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1431 return copy;
1432}
1433
1434CodeGenModule::ByrefHelpers *
1435CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1436 const AutoVarEmission &emission) {
1437 const VarDecl &var = *emission.Variable;
1438 QualType type = var.getType();
1439
1440 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1441 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1442 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1443
1444 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1445 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1446 }
1447
1448 BlockFieldFlags flags;
1449 if (type->isBlockPointerType()) {
1450 flags |= BLOCK_FIELD_IS_BLOCK;
1451 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1452 type->isObjCObjectPointerType()) {
1453 flags |= BLOCK_FIELD_IS_OBJECT;
1454 } else {
1455 return 0;
1456 }
1457
1458 if (type.isObjCGCWeak())
1459 flags |= BLOCK_FIELD_IS_WEAK;
1460
1461 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1462 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001463}
1464
John McCall5af02db2011-03-31 01:59:53 +00001465unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1466 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1467
1468 return ByRefValueInfo.find(VD)->second.second;
1469}
1470
1471llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1472 const VarDecl *V) {
1473 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1474 Loc = Builder.CreateLoad(Loc);
1475 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1476 V->getNameAsString());
1477 return Loc;
1478}
1479
1480/// BuildByRefType - This routine changes a __block variable declared as T x
1481/// into:
1482///
1483/// struct {
1484/// void *__isa;
1485/// void *__forwarding;
1486/// int32_t __flags;
1487/// int32_t __size;
1488/// void *__copy_helper; // only if needed
1489/// void *__destroy_helper; // only if needed
1490/// char padding[X]; // only if needed
1491/// T x;
1492/// } x
1493///
1494const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1495 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1496 if (Info.first)
1497 return Info.first;
1498
1499 QualType Ty = D->getType();
1500
John McCall0774cb82011-05-15 01:53:33 +00001501 llvm::SmallVector<const llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001502
1503 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1504
1505 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001506 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001507
1508 // void *__forwarding;
John McCall0774cb82011-05-15 01:53:33 +00001509 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
John McCall5af02db2011-03-31 01:59:53 +00001510
1511 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001512 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001513
1514 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001515 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001516
1517 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1518 if (HasCopyAndDispose) {
1519 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001520 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001521
1522 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001523 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001524 }
1525
1526 bool Packed = false;
1527 CharUnits Align = getContext().getDeclAlign(D);
1528 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1529 // We have to insert padding.
1530
1531 // The struct above has 2 32-bit integers.
1532 unsigned CurrentOffsetInBytes = 4 * 2;
1533
1534 // And either 2 or 4 pointers.
1535 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1536 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1537
1538 // Align the offset.
1539 unsigned AlignedOffsetInBytes =
1540 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1541
1542 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1543 if (NumPaddingBytes > 0) {
1544 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1545 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001546 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001547 if (NumPaddingBytes > 1)
1548 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1549
John McCall0774cb82011-05-15 01:53:33 +00001550 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001551
1552 // We want a packed struct.
1553 Packed = true;
1554 }
1555 }
1556
1557 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001558 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001559
John McCall0774cb82011-05-15 01:53:33 +00001560 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001561
1562 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1563 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1564 ByRefTypeHolder.get());
1565
1566 Info.first = ByRefTypeHolder.get();
1567
John McCall0774cb82011-05-15 01:53:33 +00001568 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001569
1570 return Info.first;
1571}
1572
1573/// Initialize the structural components of a __block variable, i.e.
1574/// everything but the actual object.
1575void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001576 // Find the address of the local.
1577 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001578
John McCallf0c11f72011-03-31 08:03:29 +00001579 // That's an alloca of the byref structure type.
1580 const llvm::StructType *byrefType = cast<llvm::StructType>(
1581 cast<llvm::PointerType>(addr->getType())->getElementType());
1582
1583 // Build the byref helpers if necessary. This is null if we don't need any.
1584 CodeGenModule::ByrefHelpers *helpers =
1585 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001586
1587 const VarDecl &D = *emission.Variable;
1588 QualType type = D.getType();
1589
John McCallf0c11f72011-03-31 08:03:29 +00001590 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001591
1592 // Initialize the 'isa', which is just 0 or 1.
1593 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001594 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001595 isa = 1;
1596 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1597 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1598
1599 // Store the address of the variable into its own forwarding pointer.
1600 Builder.CreateStore(addr,
1601 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1602
1603 // Blocks ABI:
1604 // c) the flags field is set to either 0 if no helper functions are
1605 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1606 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001607 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001608 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1609 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1610
John McCallf0c11f72011-03-31 08:03:29 +00001611 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1612 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001613 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1614
John McCallf0c11f72011-03-31 08:03:29 +00001615 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001616 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001617 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001618
1619 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001620 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001621 }
1622}
1623
John McCalld16c2cf2011-02-08 08:22:06 +00001624void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001625 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001626 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001627 V = Builder.CreateBitCast(V, Int8PtrTy);
1628 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001629 Builder.CreateCall2(F, V, N);
1630}
John McCall5af02db2011-03-31 01:59:53 +00001631
1632namespace {
1633 struct CallBlockRelease : EHScopeStack::Cleanup {
1634 llvm::Value *Addr;
1635 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1636
1637 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1638 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1639 }
1640 };
1641}
1642
1643/// Enter a cleanup to destroy a __block variable. Note that this
1644/// cleanup should be a no-op if the variable hasn't left the stack
1645/// yet; if a cleanup is required for the variable itself, that needs
1646/// to be done externally.
1647void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1648 // We don't enter this cleanup if we're in pure-GC mode.
1649 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1650 return;
1651
1652 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1653}