blob: e5da703a61b211a476888c13296b9c4a0fec5f54 [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 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000307 QualType thisType;
308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
309 thisType = C.getPointerType(C.getRecordType(RD));
310 else
311 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000312
313 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
314 std::pair<CharUnits,CharUnits> tinfo
315 = CGM.getContext().getTypeInfoInChars(thisType);
316 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
317
318 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
319 }
320
321 // Next, all the block captures.
322 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
323 ce = block->capture_end(); ci != ce; ++ci) {
324 const VarDecl *variable = ci->getVariable();
325
326 if (ci->isByRef()) {
327 // We have to copy/dispose of the __block reference.
328 info.NeedsCopyDispose = true;
329
John McCall6b5a61b2011-02-07 10:33:21 +0000330 // Just use void* instead of a pointer to the byref type.
331 QualType byRefPtrTy = C.VoidPtrTy;
332
333 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
334 std::pair<CharUnits,CharUnits> tinfo
335 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
336 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
337
338 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
339 &*ci, llvmType));
340 continue;
341 }
342
343 // Otherwise, build a layout chunk with the size and alignment of
344 // the declaration.
345 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
346 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
347 continue;
348 }
349
350 // Block pointers require copy/dispose.
351 if (variable->getType()->isBlockPointerType()) {
352 info.NeedsCopyDispose = true;
353
354 // So do Objective-C pointers.
355 } else if (variable->getType()->isObjCObjectPointerType() ||
356 C.isObjCNSObjectType(variable->getType())) {
357 info.NeedsCopyDispose = true;
358
359 // So do types that require non-trivial copy construction.
360 } else if (ci->hasCopyExpr()) {
361 info.NeedsCopyDispose = true;
362 info.HasCXXObject = true;
363
364 // And so do types with destructors.
365 } else if (CGM.getLangOptions().CPlusPlus) {
366 if (const CXXRecordDecl *record =
367 variable->getType()->getAsCXXRecordDecl()) {
368 if (!record->hasTrivialDestructor()) {
369 info.HasCXXObject = true;
370 info.NeedsCopyDispose = true;
371 }
372 }
373 }
374
375 CharUnits size = C.getTypeSizeInChars(variable->getType());
376 CharUnits align = C.getDeclAlign(variable);
377 maxFieldAlign = std::max(maxFieldAlign, align);
378
379 const llvm::Type *llvmType =
380 CGM.getTypes().ConvertTypeForMem(variable->getType());
381
382 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
383 }
384
385 // If that was everything, we're done here.
386 if (layout.empty()) {
387 info.StructureType =
388 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
389 info.CanBeGlobal = true;
390 return;
391 }
392
393 // Sort the layout by alignment. We have to use a stable sort here
394 // to get reproducible results. There should probably be an
395 // llvm::array_pod_stable_sort.
396 std::stable_sort(layout.begin(), layout.end());
397
398 CharUnits &blockSize = info.BlockSize;
399 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
400
401 // Assuming that the first byte in the header is maximally aligned,
402 // get the alignment of the first byte following the header.
403 CharUnits endAlign = getLowBit(blockSize);
404
405 // If the end of the header isn't satisfactorily aligned for the
406 // maximum thing, look for things that are okay with the header-end
407 // alignment, and keep appending them until we get something that's
408 // aligned right. This algorithm is only guaranteed optimal if
409 // that condition is satisfied at some point; otherwise we can get
410 // things like:
411 // header // next byte has alignment 4
412 // something_with_size_5; // next byte has alignment 1
413 // something_with_alignment_8;
414 // which has 7 bytes of padding, as opposed to the naive solution
415 // which might have less (?).
416 if (endAlign < maxFieldAlign) {
417 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
418 li = layout.begin() + 1, le = layout.end();
419
420 // Look for something that the header end is already
421 // satisfactorily aligned for.
422 for (; li != le && endAlign < li->Alignment; ++li)
423 ;
424
425 // If we found something that's naturally aligned for the end of
426 // the header, keep adding things...
427 if (li != le) {
428 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
429 for (; li != le; ++li) {
430 assert(endAlign >= li->Alignment);
431
432 li->setIndex(info, elementTypes.size());
433 elementTypes.push_back(li->Type);
434 blockSize += li->Size;
435 endAlign = getLowBit(blockSize);
436
437 // ...until we get to the alignment of the maximum field.
438 if (endAlign >= maxFieldAlign)
439 break;
440 }
441
442 // Don't re-append everything we just appended.
443 layout.erase(first, li);
444 }
445 }
446
447 // At this point, we just have to add padding if the end align still
448 // isn't aligned right.
449 if (endAlign < maxFieldAlign) {
450 CharUnits padding = maxFieldAlign - endAlign;
451
John McCall5936e332011-02-15 09:22:45 +0000452 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
453 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000454 blockSize += padding;
455
456 endAlign = getLowBit(blockSize);
457 assert(endAlign >= maxFieldAlign);
458 }
459
460 // Slam everything else on now. This works because they have
461 // strictly decreasing alignment and we expect that size is always a
462 // multiple of alignment.
463 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
464 li = layout.begin(), le = layout.end(); li != le; ++li) {
465 assert(endAlign >= li->Alignment);
466 li->setIndex(info, elementTypes.size());
467 elementTypes.push_back(li->Type);
468 blockSize += li->Size;
469 endAlign = getLowBit(blockSize);
470 }
471
472 info.StructureType =
473 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
474}
475
476/// Emit a block literal expression in the current function.
477llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
478 std::string Name = CurFn->getName();
479 CGBlockInfo blockInfo(blockExpr, Name.c_str());
480
481 // Compute information about the layout, etc., of this block.
482 computeBlockInfo(CGM, blockInfo);
483
484 // Using that metadata, generate the actual block function.
485 llvm::Constant *blockFn
486 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
487 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000488 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000489
490 // If there is nothing to capture, we can emit this as a global block.
491 if (blockInfo.CanBeGlobal)
492 return buildGlobalBlock(CGM, blockInfo, blockFn);
493
494 // Otherwise, we have to emit this as a local block.
495
496 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000497 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000498
499 // Build the block descriptor.
500 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
501
502 const llvm::Type *intTy = ConvertType(getContext().IntTy);
503
504 llvm::AllocaInst *blockAddr =
505 CreateTempAlloca(blockInfo.StructureType, "block");
506 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
507
508 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000509 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000510 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
511 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000512 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000513
514 // Initialize the block literal.
515 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000516 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000517 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
518 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
519 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
520 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
521 "block.invoke"));
522 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
523 "block.descriptor"));
524
525 // Finally, capture all the values into the block.
526 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
527
528 // First, 'this'.
529 if (blockDecl->capturesCXXThis()) {
530 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
531 blockInfo.CXXThisIndex,
532 "block.captured-this.addr");
533 Builder.CreateStore(LoadCXXThis(), addr);
534 }
535
536 // Next, captured variables.
537 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
538 ce = blockDecl->capture_end(); ci != ce; ++ci) {
539 const VarDecl *variable = ci->getVariable();
540 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
541
542 // Ignore constant captures.
543 if (capture.isConstant()) continue;
544
545 QualType type = variable->getType();
546
547 // This will be a [[type]]*, except that a byref entry will just be
548 // an i8**.
549 llvm::Value *blockField =
550 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
551 "block.captured");
552
553 // Compute the address of the thing we're going to move into the
554 // block literal.
555 llvm::Value *src;
556 if (ci->isNested()) {
557 // We need to use the capture from the enclosing block.
558 const CGBlockInfo::Capture &enclosingCapture =
559 BlockInfo->getCapture(variable);
560
561 // This is a [[type]]*, except that a byref entry wil just be an i8**.
562 src = Builder.CreateStructGEP(LoadBlockStruct(),
563 enclosingCapture.getIndex(),
564 "block.capture.addr");
565 } else {
566 // This is a [[type]]*.
567 src = LocalDeclMap[variable];
568 }
569
570 // For byrefs, we just write the pointer to the byref struct into
571 // the block field. There's no need to chase the forwarding
572 // pointer at this point, since we're building something that will
573 // live a shorter life than the stack byref anyway.
574 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000575 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000576 if (ci->isNested())
577 src = Builder.CreateLoad(src, "byref.capture");
578 else
John McCall5936e332011-02-15 09:22:45 +0000579 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000580
John McCall5936e332011-02-15 09:22:45 +0000581 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000582 Builder.CreateStore(src, blockField);
583
584 // If we have a copy constructor, evaluate that into the block field.
585 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
586 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
587
588 // If it's a reference variable, copy the reference into the block field.
589 } else if (type->isReferenceType()) {
590 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
591
592 // Otherwise, fake up a POD copy into the block field.
593 } else {
John McCallbb699b02011-02-07 18:37:40 +0000594 // We use one of these or the other depending on whether the
595 // reference is nested.
596 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
597 SourceLocation());
598 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
599 VK_LValue, SourceLocation(), /*byref*/ false);
600
601 Expr *declRef =
602 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
603
John McCall6b5a61b2011-02-07 10:33:21 +0000604 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000605 declRef, VK_RValue);
John McCalldf045202011-03-08 09:38:48 +0000606 EmitExprAsInit(&l2r, variable, blockField,
607 getContext().getDeclAlign(variable),
608 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000609 }
610
611 // Push a destructor if necessary. The semantics for when this
612 // actually gets run are really obscure.
613 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
614 PushDestructorCleanup(type, blockField);
615 }
616
617 // Cast to the converted block-pointer type, which happens (somewhat
618 // unfortunately) to be a pointer to function type.
619 llvm::Value *result =
620 Builder.CreateBitCast(blockAddr,
621 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000622
John McCall6b5a61b2011-02-07 10:33:21 +0000623 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000624}
625
626
John McCalld16c2cf2011-02-08 08:22:06 +0000627const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000628 if (BlockDescriptorType)
629 return BlockDescriptorType;
630
Mike Stumpa5448542009-02-13 15:32:32 +0000631 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000632 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000633
Mike Stumpab695142009-02-13 15:16:56 +0000634 // struct __block_descriptor {
635 // unsigned long reserved;
636 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000637 //
638 // // later, the following will be added
639 //
640 // struct {
641 // void (*copyHelper)();
642 // void (*copyHelper)();
643 // } helpers; // !!! optional
644 //
645 // const char *signature; // the block signature
646 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000647 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000648 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
649 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000650 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000651 NULL);
652
653 getModule().addTypeName("struct.__block_descriptor",
654 BlockDescriptorType);
655
John McCall6b5a61b2011-02-07 10:33:21 +0000656 // Now form a pointer to that.
657 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000658 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000659}
660
John McCalld16c2cf2011-02-08 08:22:06 +0000661const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000662 if (GenericBlockLiteralType)
663 return GenericBlockLiteralType;
664
John McCall6b5a61b2011-02-07 10:33:21 +0000665 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000666
Mike Stump9b8a7972009-02-13 15:25:34 +0000667 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000668 // void *__isa;
669 // int __flags;
670 // int __reserved;
671 // void (*__invoke)(void *);
672 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000673 // };
John McCall5936e332011-02-15 09:22:45 +0000674 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
675 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000676 IntTy,
677 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000678 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000679 BlockDescPtrTy,
680 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000681
Mike Stump9b8a7972009-02-13 15:25:34 +0000682 getModule().addTypeName("struct.__block_literal_generic",
683 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000684
Mike Stump9b8a7972009-02-13 15:25:34 +0000685 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000686}
687
Mike Stumpbd65cac2009-02-19 01:01:04 +0000688
Anders Carlssona1736c02009-12-24 21:13:40 +0000689RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
690 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000691 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000692 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000693
Anders Carlssonacfde802009-02-12 00:39:25 +0000694 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
695
696 // Get a pointer to the generic block literal.
697 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000698 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000699
700 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000701 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000702 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
703
704 // Get the function pointer from the literal.
705 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000706
John McCall5936e332011-02-15 09:22:45 +0000707 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000708
Anders Carlssonacfde802009-02-12 00:39:25 +0000709 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000710 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000711 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000712
Anders Carlsson782f3972009-04-08 23:13:16 +0000713 QualType FnType = BPT->getPointeeType();
714
Anders Carlssonacfde802009-02-12 00:39:25 +0000715 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000716 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000717 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000718
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000719 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000720 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000721
John McCall64cd2322011-03-09 08:39:33 +0000722 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000723 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000724
Mike Stump1eb44332009-09-09 15:08:12 +0000725 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000726 CGM.getTypes().getFunctionInfo(ResultType, Args,
727 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000729 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000730 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000731 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Owen Anderson96e0fc72009-07-29 22:16:19 +0000733 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000734 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Anders Carlssonacfde802009-02-12 00:39:25 +0000736 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000737 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000738}
Anders Carlssond5cab542009-02-12 17:55:02 +0000739
John McCall6b5a61b2011-02-07 10:33:21 +0000740llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
741 bool isByRef) {
742 assert(BlockInfo && "evaluating block ref without block information?");
743 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000744
John McCall6b5a61b2011-02-07 10:33:21 +0000745 // Handle constant captures.
746 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000747
John McCall6b5a61b2011-02-07 10:33:21 +0000748 llvm::Value *addr =
749 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
750 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000751
John McCall6b5a61b2011-02-07 10:33:21 +0000752 if (isByRef) {
753 // addr should be a void** right now. Load, then cast the result
754 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000755
John McCall6b5a61b2011-02-07 10:33:21 +0000756 addr = Builder.CreateLoad(addr);
757 const llvm::PointerType *byrefPointerType
758 = llvm::PointerType::get(BuildByRefType(variable), 0);
759 addr = Builder.CreateBitCast(addr, byrefPointerType,
760 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000761
John McCall6b5a61b2011-02-07 10:33:21 +0000762 // Follow the forwarding pointer.
763 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
764 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000765
John McCall6b5a61b2011-02-07 10:33:21 +0000766 // Cast back to byref* and GEP over to the actual object.
767 addr = Builder.CreateBitCast(addr, byrefPointerType);
768 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
769 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000770 }
771
John McCall6b5a61b2011-02-07 10:33:21 +0000772 if (variable->getType()->isReferenceType())
773 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000774
John McCall6b5a61b2011-02-07 10:33:21 +0000775 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000776}
777
Mike Stump67a64482009-02-14 22:16:35 +0000778llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000779CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000780 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000781 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000782
John McCall6b5a61b2011-02-07 10:33:21 +0000783 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000784 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000785
John McCall6b5a61b2011-02-07 10:33:21 +0000786 // Using that metadata, generate the actual block function.
787 llvm::Constant *blockFn;
788 {
789 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000790 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
791 blockInfo,
792 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000793 }
John McCall5936e332011-02-15 09:22:45 +0000794 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000795
John McCalld16c2cf2011-02-08 08:22:06 +0000796 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000797}
798
John McCall6b5a61b2011-02-07 10:33:21 +0000799static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
800 const CGBlockInfo &blockInfo,
801 llvm::Constant *blockFn) {
802 assert(blockInfo.CanBeGlobal);
803
804 // Generate the constants for the block literal initializer.
805 llvm::Constant *fields[BlockHeaderSize];
806
807 // isa
808 fields[0] = CGM.getNSConcreteGlobalBlock();
809
810 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000811 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
812 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
813
John McCall5936e332011-02-15 09:22:45 +0000814 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000815
816 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000817 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000818
819 // Function
820 fields[3] = blockFn;
821
822 // Descriptor
823 fields[4] = buildBlockDescriptor(CGM, blockInfo);
824
825 llvm::Constant *init =
826 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
827 /*packed*/ false);
828
829 llvm::GlobalVariable *literal =
830 new llvm::GlobalVariable(CGM.getModule(),
831 init->getType(),
832 /*constant*/ true,
833 llvm::GlobalVariable::InternalLinkage,
834 init,
835 "__block_literal_global");
836 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
837
838 // Return a constant of the appropriately-casted type.
839 const llvm::Type *requiredType =
840 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
841 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000842}
843
Mike Stump00470a12009-03-05 08:32:30 +0000844llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000845CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
846 const CGBlockInfo &blockInfo,
847 const Decl *outerFnDecl,
848 const DeclMapTy &ldm) {
849 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000850
Devang Patel6d1155b2011-03-07 21:53:18 +0000851 // Check if we should generate debug info for this block function.
852 if (CGM.getModuleDebugInfo())
853 DebugInfo = CGM.getModuleDebugInfo();
854
John McCall6b5a61b2011-02-07 10:33:21 +0000855 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Mike Stump7f28a9c2009-03-13 23:34:28 +0000857 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000858 // to be local to this function as well, in case they're directly
859 // referenced in a block.
860 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
861 const VarDecl *var = dyn_cast<VarDecl>(i->first);
862 if (var && !var->hasLocalStorage())
863 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000864 }
865
John McCall6b5a61b2011-02-07 10:33:21 +0000866 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000867
John McCall6b5a61b2011-02-07 10:33:21 +0000868 // Build the argument list.
869 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000870
John McCall6b5a61b2011-02-07 10:33:21 +0000871 // The first argument is the block pointer. Just take it as a void*
872 // and cast it later.
873 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000874 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000875
John McCall8178df32011-02-22 22:38:33 +0000876 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
877 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000878 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000879
John McCall6b5a61b2011-02-07 10:33:21 +0000880 // Now add the rest of the parameters.
881 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
882 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000883 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000884
John McCall6b5a61b2011-02-07 10:33:21 +0000885 // Create the function declaration.
886 const FunctionProtoType *fnType =
887 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
888 const CGFunctionInfo &fnInfo =
889 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
890 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000891 if (CGM.ReturnTypeUsesSRet(fnInfo))
892 blockInfo.UsesStret = true;
893
John McCall6b5a61b2011-02-07 10:33:21 +0000894 const llvm::FunctionType *fnLLVMType =
895 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000896
John McCall6b5a61b2011-02-07 10:33:21 +0000897 MangleBuffer name;
898 CGM.getBlockMangledName(GD, name, blockDecl);
899 llvm::Function *fn =
900 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
901 name.getString(), &CGM.getModule());
902 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000903
John McCall6b5a61b2011-02-07 10:33:21 +0000904 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000905 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000906 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000907 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000908
John McCall8178df32011-02-22 22:38:33 +0000909 // Okay. Undo some of what StartFunction did.
910
911 // Pull the 'self' reference out of the local decl map.
912 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
913 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000914 BlockPointer = Builder.CreateBitCast(blockAddr,
915 blockInfo.StructureType->getPointerTo(),
916 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000917
John McCallea1471e2010-05-20 01:18:31 +0000918 // If we have a C++ 'this' reference, go ahead and force it into
919 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000920 if (blockDecl->capturesCXXThis()) {
921 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
922 blockInfo.CXXThisIndex,
923 "block.captured-this");
924 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000925 }
926
John McCall6b5a61b2011-02-07 10:33:21 +0000927 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
928 // appease it.
929 if (const ObjCMethodDecl *method
930 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
931 const VarDecl *self = method->getSelfDecl();
932
933 // There might not be a capture for 'self', but if there is...
934 if (blockInfo.Captures.count(self)) {
935 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
936 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
937 capture.getIndex(),
938 "block.captured-self");
939 LocalDeclMap[self] = selfAddr;
940 }
941 }
942
943 // Also force all the constant captures.
944 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
945 ce = blockDecl->capture_end(); ci != ce; ++ci) {
946 const VarDecl *variable = ci->getVariable();
947 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
948 if (!capture.isConstant()) continue;
949
950 unsigned align = getContext().getDeclAlign(variable).getQuantity();
951
952 llvm::AllocaInst *alloca =
953 CreateMemTemp(variable->getType(), "block.captured-const");
954 alloca->setAlignment(align);
955
956 Builder.CreateStore(capture.getConstant(), alloca, align);
957
958 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000959 }
960
Mike Stumpb289b3f2009-10-01 22:29:41 +0000961 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
962 llvm::BasicBlock *entry = Builder.GetInsertBlock();
963 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
964 --entry_ptr;
965
John McCall6b5a61b2011-02-07 10:33:21 +0000966 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000967
Mike Stumpde8c5c72009-10-01 00:27:30 +0000968 // Remember where we were...
969 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000970
Mike Stumpde8c5c72009-10-01 00:27:30 +0000971 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000972 ++entry_ptr;
973 Builder.SetInsertPoint(entry, entry_ptr);
974
John McCall6b5a61b2011-02-07 10:33:21 +0000975 // Emit debug information for all the BlockDeclRefDecls.
976 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000977 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000978 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
979 ce = blockDecl->capture_end(); ci != ce; ++ci) {
980 const VarDecl *variable = ci->getVariable();
981 DI->setLocation(variable->getLocation());
982
983 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
984 if (capture.isConstant()) {
985 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
986 Builder);
987 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +0000988 }
John McCall6b5a61b2011-02-07 10:33:21 +0000989
John McCall8178df32011-02-22 22:38:33 +0000990 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +0000991 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000992 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000993 }
John McCall6b5a61b2011-02-07 10:33:21 +0000994
Mike Stumpde8c5c72009-10-01 00:27:30 +0000995 // And resume where we left off.
996 if (resume == 0)
997 Builder.ClearInsertionPoint();
998 else
999 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001000
John McCall6b5a61b2011-02-07 10:33:21 +00001001 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001002
John McCall6b5a61b2011-02-07 10:33:21 +00001003 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001004}
Mike Stumpa99038c2009-02-28 09:07:16 +00001005
John McCall6b5a61b2011-02-07 10:33:21 +00001006/*
1007 notes.push_back(HelperInfo());
1008 HelperInfo &note = notes.back();
1009 note.index = capture.getIndex();
1010 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1011 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001012
John McCall6b5a61b2011-02-07 10:33:21 +00001013 if (ci->isByRef()) {
1014 note.flag = BLOCK_FIELD_IS_BYREF;
1015 if (type.isObjCGCWeak())
1016 note.flag |= BLOCK_FIELD_IS_WEAK;
1017 } else if (type->isBlockPointerType()) {
1018 note.flag = BLOCK_FIELD_IS_BLOCK;
1019 } else {
1020 note.flag = BLOCK_FIELD_IS_OBJECT;
1021 }
1022 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001023
Mike Stump00470a12009-03-05 08:32:30 +00001024
Mike Stumpa99038c2009-02-28 09:07:16 +00001025
Mike Stumpdab514f2009-03-04 03:23:46 +00001026
Mike Stumpa4f668f2009-03-06 01:33:24 +00001027
John McCall6b5a61b2011-02-07 10:33:21 +00001028llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001029CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001030 ASTContext &C = getContext();
1031
1032 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001033 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1034 args.push_back(&dstDecl);
1035 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1036 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Mike Stumpa4f668f2009-03-06 01:33:24 +00001038 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001039 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001040
John McCall6b5a61b2011-02-07 10:33:21 +00001041 // FIXME: it would be nice if these were mergeable with things with
1042 // identical semantics.
1043 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001044
1045 llvm::Function *Fn =
1046 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001047 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001048
1049 IdentifierInfo *II
1050 = &CGM.getContext().Idents.get("__copy_helper_block_");
1051
Devang Patel58dc5ca2011-05-02 20:37:08 +00001052 // Check if we should generate debug info for this block helper function.
1053 if (CGM.getModuleDebugInfo())
1054 DebugInfo = CGM.getModuleDebugInfo();
1055
John McCall6b5a61b2011-02-07 10:33:21 +00001056 FunctionDecl *FD = FunctionDecl::Create(C,
1057 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001058 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001059 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001060 SC_Static,
1061 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001062 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001063 true);
John McCalld26bc762011-03-09 04:27:21 +00001064 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001065
John McCall6b5a61b2011-02-07 10:33:21 +00001066 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001067
John McCalld26bc762011-03-09 04:27:21 +00001068 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001069 src = Builder.CreateLoad(src);
1070 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001071
John McCalld26bc762011-03-09 04:27:21 +00001072 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001073 dst = Builder.CreateLoad(dst);
1074 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001075
John McCall6b5a61b2011-02-07 10:33:21 +00001076 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001077
John McCall6b5a61b2011-02-07 10:33:21 +00001078 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1079 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1080 const VarDecl *variable = ci->getVariable();
1081 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001082
John McCall6b5a61b2011-02-07 10:33:21 +00001083 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1084 if (capture.isConstant()) continue;
1085
1086 const Expr *copyExpr = ci->getCopyExpr();
1087 unsigned flags = 0;
1088
1089 if (copyExpr) {
1090 assert(!ci->isByRef());
1091 // don't bother computing flags
1092 } else if (ci->isByRef()) {
1093 flags = BLOCK_FIELD_IS_BYREF;
1094 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1095 } else if (type->isBlockPointerType()) {
1096 flags = BLOCK_FIELD_IS_BLOCK;
1097 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1098 flags = BLOCK_FIELD_IS_OBJECT;
1099 }
1100
1101 if (!copyExpr && !flags) continue;
1102
1103 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001104 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1105 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001106
1107 // If there's an explicit copy expression, we do that.
1108 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001109 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001110 } else {
1111 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001112 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1113 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001114 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001115 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001116 }
1117 }
1118
John McCalld16c2cf2011-02-08 08:22:06 +00001119 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001120
John McCall5936e332011-02-15 09:22:45 +00001121 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001122}
1123
John McCall6b5a61b2011-02-07 10:33:21 +00001124llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001125CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001126 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001127
John McCall6b5a61b2011-02-07 10:33:21 +00001128 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001129 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1130 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Mike Stumpa4f668f2009-03-06 01:33:24 +00001132 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001133 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001134
Mike Stump3899a7f2009-06-05 23:26:36 +00001135 // FIXME: We'd like to put these into a mergable by content, with
1136 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001137 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001138
1139 llvm::Function *Fn =
1140 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001141 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001142
Devang Patel58dc5ca2011-05-02 20:37:08 +00001143 // Check if we should generate debug info for this block destroy function.
1144 if (CGM.getModuleDebugInfo())
1145 DebugInfo = CGM.getModuleDebugInfo();
1146
Mike Stumpa4f668f2009-03-06 01:33:24 +00001147 IdentifierInfo *II
1148 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1149
John McCall6b5a61b2011-02-07 10:33:21 +00001150 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001151 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001152 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001153 SC_Static,
1154 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001155 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001156 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001157
John McCall6b5a61b2011-02-07 10:33:21 +00001158 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001159
John McCalld26bc762011-03-09 04:27:21 +00001160 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001161 src = Builder.CreateLoad(src);
1162 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001163
John McCall6b5a61b2011-02-07 10:33:21 +00001164 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1165
John McCalld16c2cf2011-02-08 08:22:06 +00001166 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001167
1168 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1169 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1170 const VarDecl *variable = ci->getVariable();
1171 QualType type = variable->getType();
1172
1173 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1174 if (capture.isConstant()) continue;
1175
John McCalld16c2cf2011-02-08 08:22:06 +00001176 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001177 const CXXDestructorDecl *dtor = 0;
1178
1179 if (ci->isByRef()) {
1180 flags = BLOCK_FIELD_IS_BYREF;
1181 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1182 } else if (type->isBlockPointerType()) {
1183 flags = BLOCK_FIELD_IS_BLOCK;
1184 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1185 flags = BLOCK_FIELD_IS_OBJECT;
1186 } else if (C.getLangOptions().CPlusPlus) {
1187 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1188 if (!record->hasTrivialDestructor())
1189 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001190 }
John McCall6b5a61b2011-02-07 10:33:21 +00001191
John McCalld16c2cf2011-02-08 08:22:06 +00001192 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001193
1194 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001195 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001196
1197 // If there's an explicit copy expression, we do that.
1198 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001199 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001200
1201 // Otherwise we call _Block_object_dispose. It wouldn't be too
1202 // hard to just emit this as a cleanup if we wanted to make sure
1203 // that things were done in reverse.
1204 } else {
1205 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001206 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001207 BuildBlockRelease(value, flags);
1208 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001209 }
1210
John McCall6b5a61b2011-02-07 10:33:21 +00001211 cleanups.ForceCleanup();
1212
John McCalld16c2cf2011-02-08 08:22:06 +00001213 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001214
John McCall5936e332011-02-15 09:22:45 +00001215 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001216}
1217
John McCallf0c11f72011-03-31 08:03:29 +00001218namespace {
1219
1220/// Emits the copy/dispose helper functions for a __block object of id type.
1221class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1222 BlockFieldFlags Flags;
1223
1224public:
1225 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1226 : ByrefHelpers(alignment), Flags(flags) {}
1227
John McCall36170192011-03-31 09:19:20 +00001228 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1229 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001230 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1231
1232 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1233 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1234
1235 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1236
1237 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1238 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1239 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1240 }
1241
1242 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1243 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1244 llvm::Value *value = CGF.Builder.CreateLoad(field);
1245
1246 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1247 }
1248
1249 void profileImpl(llvm::FoldingSetNodeID &id) const {
1250 id.AddInteger(Flags.getBitMask());
1251 }
1252};
1253
1254/// Emits the copy/dispose helpers for a __block variable with a
1255/// nontrivial copy constructor or destructor.
1256class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1257 QualType VarType;
1258 const Expr *CopyExpr;
1259
1260public:
1261 CXXByrefHelpers(CharUnits alignment, QualType type,
1262 const Expr *copyExpr)
1263 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1264
1265 bool needsCopy() const { return CopyExpr != 0; }
1266 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1267 llvm::Value *srcField) {
1268 if (!CopyExpr) return;
1269 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1270 }
1271
1272 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1273 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1274 CGF.PushDestructorCleanup(VarType, field);
1275 CGF.PopCleanupBlocks(cleanupDepth);
1276 }
1277
1278 void profileImpl(llvm::FoldingSetNodeID &id) const {
1279 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1280 }
1281};
1282} // end anonymous namespace
1283
1284static llvm::Constant *
1285generateByrefCopyHelper(CodeGenFunction &CGF,
1286 const llvm::StructType &byrefType,
1287 CodeGenModule::ByrefHelpers &byrefInfo) {
1288 ASTContext &Context = CGF.getContext();
1289
1290 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001291
John McCalld26bc762011-03-09 04:27:21 +00001292 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001293 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001294 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001295
John McCallf0c11f72011-03-31 08:03:29 +00001296 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001297 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Mike Stump45031c02009-03-06 02:29:21 +00001299 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001300 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001301
John McCallf0c11f72011-03-31 08:03:29 +00001302 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001303 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1304
Mike Stump3899a7f2009-06-05 23:26:36 +00001305 // FIXME: We'd like to put these into a mergable by content, with
1306 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001307 llvm::Function *Fn =
1308 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001309 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001310
1311 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001312 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001313
John McCallf0c11f72011-03-31 08:03:29 +00001314 FunctionDecl *FD = FunctionDecl::Create(Context,
1315 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001316 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001317 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001318 SC_Static,
1319 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001320 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001321 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001322
John McCallf0c11f72011-03-31 08:03:29 +00001323 if (byrefInfo.needsCopy()) {
1324 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001325
John McCallf0c11f72011-03-31 08:03:29 +00001326 // dst->x
1327 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1328 destField = CGF.Builder.CreateLoad(destField);
1329 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1330 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001331
John McCallf0c11f72011-03-31 08:03:29 +00001332 // src->x
1333 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1334 srcField = CGF.Builder.CreateLoad(srcField);
1335 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1336 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1337
1338 byrefInfo.emitCopy(CGF, destField, srcField);
1339 }
1340
1341 CGF.FinishFunction();
1342
1343 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001344}
1345
John McCallf0c11f72011-03-31 08:03:29 +00001346/// Build the copy helper for a __block variable.
1347static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1348 const llvm::StructType &byrefType,
1349 CodeGenModule::ByrefHelpers &info) {
1350 CodeGenFunction CGF(CGM);
1351 return generateByrefCopyHelper(CGF, byrefType, info);
1352}
1353
1354/// Generate code for a __block variable's dispose helper.
1355static llvm::Constant *
1356generateByrefDisposeHelper(CodeGenFunction &CGF,
1357 const llvm::StructType &byrefType,
1358 CodeGenModule::ByrefHelpers &byrefInfo) {
1359 ASTContext &Context = CGF.getContext();
1360 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001361
John McCalld26bc762011-03-09 04:27:21 +00001362 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001363 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001364 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Mike Stump45031c02009-03-06 02:29:21 +00001366 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001367 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001368
John McCallf0c11f72011-03-31 08:03:29 +00001369 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001370 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1371
Mike Stump3899a7f2009-06-05 23:26:36 +00001372 // FIXME: We'd like to put these into a mergable by content, with
1373 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001374 llvm::Function *Fn =
1375 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001376 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001377 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001378
1379 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001380 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001381
John McCallf0c11f72011-03-31 08:03:29 +00001382 FunctionDecl *FD = FunctionDecl::Create(Context,
1383 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001384 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001385 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001386 SC_Static,
1387 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001388 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001389 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001390
John McCallf0c11f72011-03-31 08:03:29 +00001391 if (byrefInfo.needsDispose()) {
1392 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1393 V = CGF.Builder.CreateLoad(V);
1394 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1395 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001396
John McCallf0c11f72011-03-31 08:03:29 +00001397 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001398 }
Mike Stump45031c02009-03-06 02:29:21 +00001399
John McCallf0c11f72011-03-31 08:03:29 +00001400 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001401
John McCallf0c11f72011-03-31 08:03:29 +00001402 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001403}
1404
John McCallf0c11f72011-03-31 08:03:29 +00001405/// Build the dispose helper for a __block variable.
1406static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1407 const llvm::StructType &byrefType,
1408 CodeGenModule::ByrefHelpers &info) {
1409 CodeGenFunction CGF(CGM);
1410 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001411}
1412
John McCallf0c11f72011-03-31 08:03:29 +00001413///
1414template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1415 const llvm::StructType &byrefTy,
1416 T &byrefInfo) {
1417 // Increase the field's alignment to be at least pointer alignment,
1418 // since the layout of the byref struct will guarantee at least that.
1419 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1420 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1421
1422 llvm::FoldingSetNodeID id;
1423 byrefInfo.Profile(id);
1424
1425 void *insertPos;
1426 CodeGenModule::ByrefHelpers *node
1427 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1428 if (node) return static_cast<T*>(node);
1429
1430 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1431 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1432
1433 T *copy = new (CGM.getContext()) T(byrefInfo);
1434 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1435 return copy;
1436}
1437
1438CodeGenModule::ByrefHelpers *
1439CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1440 const AutoVarEmission &emission) {
1441 const VarDecl &var = *emission.Variable;
1442 QualType type = var.getType();
1443
1444 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1445 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1446 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1447
1448 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1449 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1450 }
1451
1452 BlockFieldFlags flags;
1453 if (type->isBlockPointerType()) {
1454 flags |= BLOCK_FIELD_IS_BLOCK;
1455 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1456 type->isObjCObjectPointerType()) {
1457 flags |= BLOCK_FIELD_IS_OBJECT;
1458 } else {
1459 return 0;
1460 }
1461
1462 if (type.isObjCGCWeak())
1463 flags |= BLOCK_FIELD_IS_WEAK;
1464
1465 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1466 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001467}
1468
John McCall5af02db2011-03-31 01:59:53 +00001469unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1470 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1471
1472 return ByRefValueInfo.find(VD)->second.second;
1473}
1474
1475llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1476 const VarDecl *V) {
1477 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1478 Loc = Builder.CreateLoad(Loc);
1479 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1480 V->getNameAsString());
1481 return Loc;
1482}
1483
1484/// BuildByRefType - This routine changes a __block variable declared as T x
1485/// into:
1486///
1487/// struct {
1488/// void *__isa;
1489/// void *__forwarding;
1490/// int32_t __flags;
1491/// int32_t __size;
1492/// void *__copy_helper; // only if needed
1493/// void *__destroy_helper; // only if needed
1494/// char padding[X]; // only if needed
1495/// T x;
1496/// } x
1497///
1498const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1499 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1500 if (Info.first)
1501 return Info.first;
1502
1503 QualType Ty = D->getType();
1504
John McCall0774cb82011-05-15 01:53:33 +00001505 llvm::SmallVector<const llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001506
1507 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1508
1509 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001510 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001511
1512 // void *__forwarding;
John McCall0774cb82011-05-15 01:53:33 +00001513 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
John McCall5af02db2011-03-31 01:59:53 +00001514
1515 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001516 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001517
1518 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001519 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001520
1521 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1522 if (HasCopyAndDispose) {
1523 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001524 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001525
1526 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001527 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001528 }
1529
1530 bool Packed = false;
1531 CharUnits Align = getContext().getDeclAlign(D);
1532 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1533 // We have to insert padding.
1534
1535 // The struct above has 2 32-bit integers.
1536 unsigned CurrentOffsetInBytes = 4 * 2;
1537
1538 // And either 2 or 4 pointers.
1539 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1540 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1541
1542 // Align the offset.
1543 unsigned AlignedOffsetInBytes =
1544 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1545
1546 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1547 if (NumPaddingBytes > 0) {
1548 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1549 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001550 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001551 if (NumPaddingBytes > 1)
1552 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1553
John McCall0774cb82011-05-15 01:53:33 +00001554 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001555
1556 // We want a packed struct.
1557 Packed = true;
1558 }
1559 }
1560
1561 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001562 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001563
John McCall0774cb82011-05-15 01:53:33 +00001564 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001565
1566 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1567 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1568 ByRefTypeHolder.get());
1569
1570 Info.first = ByRefTypeHolder.get();
1571
John McCall0774cb82011-05-15 01:53:33 +00001572 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001573
1574 return Info.first;
1575}
1576
1577/// Initialize the structural components of a __block variable, i.e.
1578/// everything but the actual object.
1579void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001580 // Find the address of the local.
1581 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001582
John McCallf0c11f72011-03-31 08:03:29 +00001583 // That's an alloca of the byref structure type.
1584 const llvm::StructType *byrefType = cast<llvm::StructType>(
1585 cast<llvm::PointerType>(addr->getType())->getElementType());
1586
1587 // Build the byref helpers if necessary. This is null if we don't need any.
1588 CodeGenModule::ByrefHelpers *helpers =
1589 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001590
1591 const VarDecl &D = *emission.Variable;
1592 QualType type = D.getType();
1593
John McCallf0c11f72011-03-31 08:03:29 +00001594 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001595
1596 // Initialize the 'isa', which is just 0 or 1.
1597 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001598 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001599 isa = 1;
1600 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1601 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1602
1603 // Store the address of the variable into its own forwarding pointer.
1604 Builder.CreateStore(addr,
1605 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1606
1607 // Blocks ABI:
1608 // c) the flags field is set to either 0 if no helper functions are
1609 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1610 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001611 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001612 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1613 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1614
John McCallf0c11f72011-03-31 08:03:29 +00001615 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1616 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001617 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1618
John McCallf0c11f72011-03-31 08:03:29 +00001619 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001620 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001621 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001622
1623 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001624 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001625 }
1626}
1627
John McCalld16c2cf2011-02-08 08:22:06 +00001628void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001629 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001630 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001631 V = Builder.CreateBitCast(V, Int8PtrTy);
1632 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001633 Builder.CreateCall2(F, V, N);
1634}
John McCall5af02db2011-03-31 01:59:53 +00001635
1636namespace {
1637 struct CallBlockRelease : EHScopeStack::Cleanup {
1638 llvm::Value *Addr;
1639 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1640
1641 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1642 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1643 }
1644 };
1645}
1646
1647/// Enter a cleanup to destroy a __block variable. Note that this
1648/// cleanup should be a no-op if the variable hasn't left the stack
1649/// yet; if a cleanup is required for the variable itself, that needs
1650/// to be done externally.
1651void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1652 // We don't enter this cleanup if we're in pure-GC mode.
1653 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1654 return;
1655
1656 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1657}