blob: 76a68b1526ebcfd5529a81b78c57e79218758692 [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),
30 HasCXXObject(false), HasWeakBlockVariable(false),
31 StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000032
33 // Skip asm prefix, if any.
34 if (Name && Name[0] == '\01')
35 ++Name;
36}
37
John McCall6b5a61b2011-02-07 10:33:21 +000038/// Build the given block as a global block.
39static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
40 const CGBlockInfo &blockInfo,
41 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000042
John McCall6b5a61b2011-02-07 10:33:21 +000043/// Build the helper function to copy a block.
44static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
45 const CGBlockInfo &blockInfo) {
46 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
47}
48
49/// Build the helper function to dipose of a block.
50static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo) {
52 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
53}
54
55/// Build the block descriptor constant for a block.
56static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
57 const CGBlockInfo &blockInfo) {
58 ASTContext &C = CGM.getContext();
59
60 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
61 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
62
63 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000064
65 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000066 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000067
68 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000069 // FIXME: What is the right way to say this doesn't fit? We should give
70 // a user diagnostic in that case. Better fix would be to change the
71 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000072 elements.push_back(llvm::ConstantInt::get(ulong,
73 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000074
John McCall6b5a61b2011-02-07 10:33:21 +000075 // Optional copy/dispose helpers.
76 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000077 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000078 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000079
80 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000081 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000082 }
83
John McCall6b5a61b2011-02-07 10:33:21 +000084 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
85 std::string typeAtEncoding =
86 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
87 elements.push_back(llvm::ConstantExpr::getBitCast(
88 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000089
John McCall6b5a61b2011-02-07 10:33:21 +000090 // GC layout.
91 if (C.getLangOptions().ObjC1)
92 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
93 else
94 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000095
John McCall6b5a61b2011-02-07 10:33:21 +000096 llvm::Constant *init =
97 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
98 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +000099
John McCall6b5a61b2011-02-07 10:33:21 +0000100 llvm::GlobalVariable *global =
101 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
102 llvm::GlobalValue::InternalLinkage,
103 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000104
John McCall6b5a61b2011-02-07 10:33:21 +0000105 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000106}
107
John McCalld16c2cf2011-02-08 08:22:06 +0000108static BlockFlags computeBlockFlag(CodeGenModule &CGM,
109 const BlockExpr *BE,
110 BlockFlags flags) {
111 const FunctionType *ftype = BE->getFunctionType();
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000112
John McCalld16c2cf2011-02-08 08:22:06 +0000113 // This is a bit overboard.
114 CallArgList args;
115 const CGFunctionInfo &fnInfo =
116 CGM.getTypes().getFunctionInfo(ftype->getResultType(), args,
117 ftype->getExtInfo());
118
119 if (CGM.ReturnTypeUsesSRet(fnInfo))
120 flags |= BLOCK_USE_STRET;
121
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000122 return flags;
123}
124
John McCall6b5a61b2011-02-07 10:33:21 +0000125/*
126 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000127
John McCall6b5a61b2011-02-07 10:33:21 +0000128 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
129 struct Block_literal {
130 /// Initialized to one of:
131 /// extern void *_NSConcreteStackBlock[];
132 /// extern void *_NSConcreteGlobalBlock[];
133 ///
134 /// In theory, we could start one off malloc'ed by setting
135 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
136 /// this isa:
137 /// extern void *_NSConcreteMallocBlock[];
138 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000139
John McCall6b5a61b2011-02-07 10:33:21 +0000140 /// These are the flags (with corresponding bit number) that the
141 /// compiler is actually supposed to know about.
142 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
143 /// descriptor provides copy and dispose helper functions
144 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
145 /// object with a nontrivial destructor or copy constructor
146 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
147 /// as global memory
148 /// 29. BLOCK_USE_STRET - indicates that the block function
149 /// uses stret, which objc_msgSend needs to know about
150 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
151 /// @encoded signature string
152 /// And we're not supposed to manipulate these:
153 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
154 /// to malloc'ed memory
155 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
156 /// to GC-allocated memory
157 /// Additionally, the bottom 16 bits are a reference count which
158 /// should be zero on the stack.
159 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000160
John McCall6b5a61b2011-02-07 10:33:21 +0000161 /// Reserved; should be zero-initialized.
162 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000163
John McCall6b5a61b2011-02-07 10:33:21 +0000164 /// Function pointer generated from block literal.
165 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000166
John McCall6b5a61b2011-02-07 10:33:21 +0000167 /// Block description metadata generated from block literal.
168 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000169
John McCall6b5a61b2011-02-07 10:33:21 +0000170 /// Captured values follow.
171 _CapturesTypes captures...;
172 };
173 */
David Chisnall5e530af2009-11-17 19:33:30 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175/// The number of fields in a block header.
176const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000177
John McCall6b5a61b2011-02-07 10:33:21 +0000178namespace {
179 /// A chunk of data that we actually have to capture in the block.
180 struct BlockLayoutChunk {
181 CharUnits Alignment;
182 CharUnits Size;
183 const BlockDecl::Capture *Capture; // null for 'this'
184 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 BlockLayoutChunk(CharUnits align, CharUnits size,
187 const BlockDecl::Capture *capture,
188 const llvm::Type *type)
189 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000190
John McCall6b5a61b2011-02-07 10:33:21 +0000191 /// Tell the block info that this chunk has the given field index.
192 void setIndex(CGBlockInfo &info, unsigned index) {
193 if (!Capture)
194 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000195 else
John McCall6b5a61b2011-02-07 10:33:21 +0000196 info.Captures[Capture->getVariable()]
197 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000198 }
John McCall6b5a61b2011-02-07 10:33:21 +0000199 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000200
John McCall6b5a61b2011-02-07 10:33:21 +0000201 /// Order by descending alignment.
202 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
203 return left.Alignment > right.Alignment;
204 }
205}
206
John McCall461c9c12011-02-08 03:07:00 +0000207/// Determines if the given record type has a mutable field.
208static bool hasMutableField(const CXXRecordDecl *record) {
209 for (CXXRecordDecl::field_iterator
210 i = record->field_begin(), e = record->field_end(); i != e; ++i)
211 if ((*i)->isMutable())
212 return true;
213
214 for (CXXRecordDecl::base_class_const_iterator
215 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
216 const RecordType *record = i->getType()->castAs<RecordType>();
217 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
218 return true;
219 }
220
221 return false;
222}
223
224/// Determines if the given type is safe for constant capture in C++.
225static bool isSafeForCXXConstantCapture(QualType type) {
226 const RecordType *recordType =
227 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
228
229 // Only records can be unsafe.
230 if (!recordType) return true;
231
232 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
233
234 // Maintain semantics for classes with non-trivial dtors or copy ctors.
235 if (!record->hasTrivialDestructor()) return false;
236 if (!record->hasTrivialCopyConstructor()) return false;
237
238 // Otherwise, we just have to make sure there aren't any mutable
239 // fields that might have changed since initialization.
240 return !hasMutableField(record);
241}
242
John McCall6b5a61b2011-02-07 10:33:21 +0000243/// It is illegal to modify a const object after initialization.
244/// Therefore, if a const object has a constant initializer, we don't
245/// actually need to keep storage for it in the block; we'll just
246/// rematerialize it at the start of the block function. This is
247/// acceptable because we make no promises about address stability of
248/// captured variables.
249static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
250 const VarDecl *var) {
251 QualType type = var->getType();
252
253 // We can only do this if the variable is const.
254 if (!type.isConstQualified()) return 0;
255
John McCall461c9c12011-02-08 03:07:00 +0000256 // Furthermore, in C++ we have to worry about mutable fields:
257 // C++ [dcl.type.cv]p4:
258 // Except that any class member declared mutable can be
259 // modified, any attempt to modify a const object during its
260 // lifetime results in undefined behavior.
261 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000262 return 0;
263
264 // If the variable doesn't have any initializer (shouldn't this be
265 // invalid?), it's not clear what we should do. Maybe capture as
266 // zero?
267 const Expr *init = var->getInit();
268 if (!init) return 0;
269
270 return CGM.EmitConstantExpr(init, var->getType());
271}
272
273/// Get the low bit of a nonzero character count. This is the
274/// alignment of the nth byte if the 0th byte is universally aligned.
275static CharUnits getLowBit(CharUnits v) {
276 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
277}
278
279static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
280 std::vector<const llvm::Type*> &elementTypes) {
281 ASTContext &C = CGM.getContext();
282
283 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
284 CharUnits ptrSize, ptrAlign, intSize, intAlign;
285 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
286 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
287
288 // Are there crazy embedded platforms where this isn't true?
289 assert(intSize <= ptrSize && "layout assumptions horribly violated");
290
291 CharUnits headerSize = ptrSize;
292 if (2 * intSize < ptrAlign) headerSize += ptrSize;
293 else headerSize += 2 * intSize;
294 headerSize += 2 * ptrSize;
295
296 info.BlockAlign = ptrAlign;
297 info.BlockSize = headerSize;
298
299 assert(elementTypes.empty());
300 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
301 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
302 elementTypes.push_back(i8p);
303 elementTypes.push_back(intTy);
304 elementTypes.push_back(intTy);
305 elementTypes.push_back(i8p);
306 elementTypes.push_back(CGM.getBlockDescriptorType());
307
308 assert(elementTypes.size() == BlockHeaderSize);
309}
310
311/// Compute the layout of the given block. Attempts to lay the block
312/// out with minimal space requirements.
313static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
314 ASTContext &C = CGM.getContext();
315 const BlockDecl *block = info.getBlockDecl();
316
317 std::vector<const llvm::Type*> elementTypes;
318 initializeForBlockHeader(CGM, info, elementTypes);
319
320 if (!block->hasCaptures()) {
321 info.StructureType =
322 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
323 info.CanBeGlobal = true;
324 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000325 }
Mike Stump00470a12009-03-05 08:32:30 +0000326
John McCall6b5a61b2011-02-07 10:33:21 +0000327 // Collect the layout chunks.
328 llvm::SmallVector<BlockLayoutChunk, 16> layout;
329 layout.reserve(block->capturesCXXThis() +
330 (block->capture_end() - block->capture_begin()));
331
332 CharUnits maxFieldAlign;
333
334 // First, 'this'.
335 if (block->capturesCXXThis()) {
336 const DeclContext *DC = block->getDeclContext();
337 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
338 ;
339 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
340
341 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
342 std::pair<CharUnits,CharUnits> tinfo
343 = CGM.getContext().getTypeInfoInChars(thisType);
344 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
345
346 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
347 }
348
349 // Next, all the block captures.
350 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
351 ce = block->capture_end(); ci != ce; ++ci) {
352 const VarDecl *variable = ci->getVariable();
353
354 if (ci->isByRef()) {
355 // We have to copy/dispose of the __block reference.
356 info.NeedsCopyDispose = true;
357
358 // Also note that it's weak for GC purposes.
359 if (variable->getType().isObjCGCWeak())
360 info.HasWeakBlockVariable = true;
361
362 // Just use void* instead of a pointer to the byref type.
363 QualType byRefPtrTy = C.VoidPtrTy;
364
365 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
366 std::pair<CharUnits,CharUnits> tinfo
367 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
368 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
369
370 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
371 &*ci, llvmType));
372 continue;
373 }
374
375 // Otherwise, build a layout chunk with the size and alignment of
376 // the declaration.
377 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
378 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
379 continue;
380 }
381
382 // Block pointers require copy/dispose.
383 if (variable->getType()->isBlockPointerType()) {
384 info.NeedsCopyDispose = true;
385
386 // So do Objective-C pointers.
387 } else if (variable->getType()->isObjCObjectPointerType() ||
388 C.isObjCNSObjectType(variable->getType())) {
389 info.NeedsCopyDispose = true;
390
391 // So do types that require non-trivial copy construction.
392 } else if (ci->hasCopyExpr()) {
393 info.NeedsCopyDispose = true;
394 info.HasCXXObject = true;
395
396 // And so do types with destructors.
397 } else if (CGM.getLangOptions().CPlusPlus) {
398 if (const CXXRecordDecl *record =
399 variable->getType()->getAsCXXRecordDecl()) {
400 if (!record->hasTrivialDestructor()) {
401 info.HasCXXObject = true;
402 info.NeedsCopyDispose = true;
403 }
404 }
405 }
406
407 CharUnits size = C.getTypeSizeInChars(variable->getType());
408 CharUnits align = C.getDeclAlign(variable);
409 maxFieldAlign = std::max(maxFieldAlign, align);
410
411 const llvm::Type *llvmType =
412 CGM.getTypes().ConvertTypeForMem(variable->getType());
413
414 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
415 }
416
417 // If that was everything, we're done here.
418 if (layout.empty()) {
419 info.StructureType =
420 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
421 info.CanBeGlobal = true;
422 return;
423 }
424
425 // Sort the layout by alignment. We have to use a stable sort here
426 // to get reproducible results. There should probably be an
427 // llvm::array_pod_stable_sort.
428 std::stable_sort(layout.begin(), layout.end());
429
430 CharUnits &blockSize = info.BlockSize;
431 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
432
433 // Assuming that the first byte in the header is maximally aligned,
434 // get the alignment of the first byte following the header.
435 CharUnits endAlign = getLowBit(blockSize);
436
437 // If the end of the header isn't satisfactorily aligned for the
438 // maximum thing, look for things that are okay with the header-end
439 // alignment, and keep appending them until we get something that's
440 // aligned right. This algorithm is only guaranteed optimal if
441 // that condition is satisfied at some point; otherwise we can get
442 // things like:
443 // header // next byte has alignment 4
444 // something_with_size_5; // next byte has alignment 1
445 // something_with_alignment_8;
446 // which has 7 bytes of padding, as opposed to the naive solution
447 // which might have less (?).
448 if (endAlign < maxFieldAlign) {
449 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
450 li = layout.begin() + 1, le = layout.end();
451
452 // Look for something that the header end is already
453 // satisfactorily aligned for.
454 for (; li != le && endAlign < li->Alignment; ++li)
455 ;
456
457 // If we found something that's naturally aligned for the end of
458 // the header, keep adding things...
459 if (li != le) {
460 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
461 for (; li != le; ++li) {
462 assert(endAlign >= li->Alignment);
463
464 li->setIndex(info, elementTypes.size());
465 elementTypes.push_back(li->Type);
466 blockSize += li->Size;
467 endAlign = getLowBit(blockSize);
468
469 // ...until we get to the alignment of the maximum field.
470 if (endAlign >= maxFieldAlign)
471 break;
472 }
473
474 // Don't re-append everything we just appended.
475 layout.erase(first, li);
476 }
477 }
478
479 // At this point, we just have to add padding if the end align still
480 // isn't aligned right.
481 if (endAlign < maxFieldAlign) {
482 CharUnits padding = maxFieldAlign - endAlign;
483
484 const llvm::Type *i8 = llvm::IntegerType::get(CGM.getLLVMContext(), 8);
485 elementTypes.push_back(llvm::ArrayType::get(i8, padding.getQuantity()));
486 blockSize += padding;
487
488 endAlign = getLowBit(blockSize);
489 assert(endAlign >= maxFieldAlign);
490 }
491
492 // Slam everything else on now. This works because they have
493 // strictly decreasing alignment and we expect that size is always a
494 // multiple of alignment.
495 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
496 li = layout.begin(), le = layout.end(); li != le; ++li) {
497 assert(endAlign >= li->Alignment);
498 li->setIndex(info, elementTypes.size());
499 elementTypes.push_back(li->Type);
500 blockSize += li->Size;
501 endAlign = getLowBit(blockSize);
502 }
503
504 info.StructureType =
505 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
506}
507
508/// Emit a block literal expression in the current function.
509llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
510 std::string Name = CurFn->getName();
511 CGBlockInfo blockInfo(blockExpr, Name.c_str());
512
513 // Compute information about the layout, etc., of this block.
514 computeBlockInfo(CGM, blockInfo);
515
516 // Using that metadata, generate the actual block function.
517 llvm::Constant *blockFn
518 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
519 CurFuncDecl, LocalDeclMap);
John McCalld16c2cf2011-02-08 08:22:06 +0000520 blockFn = llvm::ConstantExpr::getBitCast(blockFn, Int8PtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000521
522 // If there is nothing to capture, we can emit this as a global block.
523 if (blockInfo.CanBeGlobal)
524 return buildGlobalBlock(CGM, blockInfo, blockFn);
525
526 // Otherwise, we have to emit this as a local block.
527
528 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalld16c2cf2011-02-08 08:22:06 +0000529 isa = llvm::ConstantExpr::getBitCast(isa, Int8PtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000530
531 // Build the block descriptor.
532 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
533
534 const llvm::Type *intTy = ConvertType(getContext().IntTy);
535
536 llvm::AllocaInst *blockAddr =
537 CreateTempAlloca(blockInfo.StructureType, "block");
538 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
539
540 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000541 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000542 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
543 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
544 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
545
546 // Initialize the block literal.
547 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000548 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000549 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
550 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
551 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
552 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
553 "block.invoke"));
554 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
555 "block.descriptor"));
556
557 // Finally, capture all the values into the block.
558 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
559
560 // First, 'this'.
561 if (blockDecl->capturesCXXThis()) {
562 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
563 blockInfo.CXXThisIndex,
564 "block.captured-this.addr");
565 Builder.CreateStore(LoadCXXThis(), addr);
566 }
567
568 // Next, captured variables.
569 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
570 ce = blockDecl->capture_end(); ci != ce; ++ci) {
571 const VarDecl *variable = ci->getVariable();
572 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
573
574 // Ignore constant captures.
575 if (capture.isConstant()) continue;
576
577 QualType type = variable->getType();
578
579 // This will be a [[type]]*, except that a byref entry will just be
580 // an i8**.
581 llvm::Value *blockField =
582 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
583 "block.captured");
584
585 // Compute the address of the thing we're going to move into the
586 // block literal.
587 llvm::Value *src;
588 if (ci->isNested()) {
589 // We need to use the capture from the enclosing block.
590 const CGBlockInfo::Capture &enclosingCapture =
591 BlockInfo->getCapture(variable);
592
593 // This is a [[type]]*, except that a byref entry wil just be an i8**.
594 src = Builder.CreateStructGEP(LoadBlockStruct(),
595 enclosingCapture.getIndex(),
596 "block.capture.addr");
597 } else {
598 // This is a [[type]]*.
599 src = LocalDeclMap[variable];
600 }
601
602 // For byrefs, we just write the pointer to the byref struct into
603 // the block field. There's no need to chase the forwarding
604 // pointer at this point, since we're building something that will
605 // live a shorter life than the stack byref anyway.
606 if (ci->isByRef()) {
607 // Get an i8* that points to the byref struct.
608 if (ci->isNested())
609 src = Builder.CreateLoad(src, "byref.capture");
610 else
John McCalld16c2cf2011-02-08 08:22:06 +0000611 src = Builder.CreateBitCast(src, Int8PtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000612
613 // Write that i8* into the capture field.
614 Builder.CreateStore(src, blockField);
615
616 // If we have a copy constructor, evaluate that into the block field.
617 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
618 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
619
620 // If it's a reference variable, copy the reference into the block field.
621 } else if (type->isReferenceType()) {
622 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
623
624 // Otherwise, fake up a POD copy into the block field.
625 } else {
John McCallbb699b02011-02-07 18:37:40 +0000626 // We use one of these or the other depending on whether the
627 // reference is nested.
628 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
629 SourceLocation());
630 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
631 VK_LValue, SourceLocation(), /*byref*/ false);
632
633 Expr *declRef =
634 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
635
John McCall6b5a61b2011-02-07 10:33:21 +0000636 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000637 declRef, VK_RValue);
John McCall6b5a61b2011-02-07 10:33:21 +0000638 EmitAnyExprToMem(&l2r, blockField, /*volatile*/ false, /*init*/ true);
639 }
640
641 // Push a destructor if necessary. The semantics for when this
642 // actually gets run are really obscure.
643 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
644 PushDestructorCleanup(type, blockField);
645 }
646
647 // Cast to the converted block-pointer type, which happens (somewhat
648 // unfortunately) to be a pointer to function type.
649 llvm::Value *result =
650 Builder.CreateBitCast(blockAddr,
651 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000652
653 // We must call objc_read_weak on the block literal itself if it closes
654 // on any __weak __block variables. For some reason.
John McCall6b5a61b2011-02-07 10:33:21 +0000655 if (blockInfo.HasWeakBlockVariable) {
656 const llvm::Type *OrigTy = result->getType();
John McCall711c52b2011-01-05 12:14:39 +0000657
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000658 // Must cast argument to id*
659 const llvm::Type *ObjectPtrTy =
660 ConvertType(CGM.getContext().getObjCIdType());
661 const llvm::Type *PtrObjectPtrTy =
662 llvm::PointerType::getUnqual(ObjectPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000663 result = Builder.CreateBitCast(result, PtrObjectPtrTy);
664 result = CGM.getObjCRuntime().EmitObjCWeakRead(*this, result);
John McCall711c52b2011-01-05 12:14:39 +0000665
666 // Cast back to the original type.
John McCall6b5a61b2011-02-07 10:33:21 +0000667 result = Builder.CreateBitCast(result, OrigTy);
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000668 }
John McCall6b5a61b2011-02-07 10:33:21 +0000669 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000670}
671
672
John McCalld16c2cf2011-02-08 08:22:06 +0000673const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000674 if (BlockDescriptorType)
675 return BlockDescriptorType;
676
Mike Stumpa5448542009-02-13 15:32:32 +0000677 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000678 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000679
Mike Stumpab695142009-02-13 15:16:56 +0000680 // struct __block_descriptor {
681 // unsigned long reserved;
682 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000683 //
684 // // later, the following will be added
685 //
686 // struct {
687 // void (*copyHelper)();
688 // void (*copyHelper)();
689 // } helpers; // !!! optional
690 //
691 // const char *signature; // the block signature
692 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000693 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000694 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
695 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000696 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000697 NULL);
698
699 getModule().addTypeName("struct.__block_descriptor",
700 BlockDescriptorType);
701
John McCall6b5a61b2011-02-07 10:33:21 +0000702 // Now form a pointer to that.
703 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000704 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000705}
706
John McCalld16c2cf2011-02-08 08:22:06 +0000707const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000708 if (GenericBlockLiteralType)
709 return GenericBlockLiteralType;
710
John McCall6b5a61b2011-02-07 10:33:21 +0000711 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000712
Mike Stump7cbb3602009-02-13 16:01:35 +0000713 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
714 getTypes().ConvertType(getContext().IntTy));
715
Mike Stump9b8a7972009-02-13 15:25:34 +0000716 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000717 // void *__isa;
718 // int __flags;
719 // int __reserved;
720 // void (*__invoke)(void *);
721 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000722 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000723 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
John McCalld16c2cf2011-02-08 08:22:06 +0000724 Int8PtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000725 IntTy,
726 IntTy,
John McCalld16c2cf2011-02-08 08:22:06 +0000727 Int8PtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000728 BlockDescPtrTy,
729 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000730
Mike Stump9b8a7972009-02-13 15:25:34 +0000731 getModule().addTypeName("struct.__block_literal_generic",
732 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000733
Mike Stump9b8a7972009-02-13 15:25:34 +0000734 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000735}
736
Mike Stumpbd65cac2009-02-19 01:01:04 +0000737
Anders Carlssona1736c02009-12-24 21:13:40 +0000738RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
739 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000740 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000741 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000742
Anders Carlssonacfde802009-02-12 00:39:25 +0000743 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
744
745 // Get a pointer to the generic block literal.
746 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000747 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000748
749 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000750 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000751 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
752
753 // Get the function pointer from the literal.
754 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000755
John McCalld16c2cf2011-02-08 08:22:06 +0000756 BlockLiteral = Builder.CreateBitCast(BlockLiteral, Int8PtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000757
Anders Carlssonacfde802009-02-12 00:39:25 +0000758 // Add the block literal.
759 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
760 CallArgList Args;
761 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000762
Anders Carlsson782f3972009-04-08 23:13:16 +0000763 QualType FnType = BPT->getPointeeType();
764
Anders Carlssonacfde802009-02-12 00:39:25 +0000765 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000766 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000767 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000768
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000769 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000770 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000771
John McCall04a67a62010-02-05 21:31:56 +0000772 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
773 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000774
Mike Stump1eb44332009-09-09 15:08:12 +0000775 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000776 CGM.getTypes().getFunctionInfo(ResultType, Args,
777 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000779 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000780 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000781 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Owen Anderson96e0fc72009-07-29 22:16:19 +0000783 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000784 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Anders Carlssonacfde802009-02-12 00:39:25 +0000786 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000787 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000788}
Anders Carlssond5cab542009-02-12 17:55:02 +0000789
John McCall6b5a61b2011-02-07 10:33:21 +0000790llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
791 bool isByRef) {
792 assert(BlockInfo && "evaluating block ref without block information?");
793 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 // Handle constant captures.
796 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000797
John McCall6b5a61b2011-02-07 10:33:21 +0000798 llvm::Value *addr =
799 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
800 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000801
John McCall6b5a61b2011-02-07 10:33:21 +0000802 if (isByRef) {
803 // addr should be a void** right now. Load, then cast the result
804 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000805
John McCall6b5a61b2011-02-07 10:33:21 +0000806 addr = Builder.CreateLoad(addr);
807 const llvm::PointerType *byrefPointerType
808 = llvm::PointerType::get(BuildByRefType(variable), 0);
809 addr = Builder.CreateBitCast(addr, byrefPointerType,
810 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000811
John McCall6b5a61b2011-02-07 10:33:21 +0000812 // Follow the forwarding pointer.
813 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
814 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000815
John McCall6b5a61b2011-02-07 10:33:21 +0000816 // Cast back to byref* and GEP over to the actual object.
817 addr = Builder.CreateBitCast(addr, byrefPointerType);
818 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
819 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000820 }
821
John McCall6b5a61b2011-02-07 10:33:21 +0000822 if (variable->getType()->isReferenceType())
823 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000824
John McCall6b5a61b2011-02-07 10:33:21 +0000825 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000826}
827
Mike Stump67a64482009-02-14 22:16:35 +0000828llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000829CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall6b5a61b2011-02-07 10:33:21 +0000830 const char *name) {
831 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000832
John McCall6b5a61b2011-02-07 10:33:21 +0000833 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000834 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000835
John McCall6b5a61b2011-02-07 10:33:21 +0000836 // Using that metadata, generate the actual block function.
837 llvm::Constant *blockFn;
838 {
839 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000840 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
841 blockInfo,
842 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000843 }
John McCalld16c2cf2011-02-08 08:22:06 +0000844 blockFn = llvm::ConstantExpr::getBitCast(blockFn, Int8PtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000845
John McCalld16c2cf2011-02-08 08:22:06 +0000846 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000847}
848
John McCall6b5a61b2011-02-07 10:33:21 +0000849static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
850 const CGBlockInfo &blockInfo,
851 llvm::Constant *blockFn) {
852 assert(blockInfo.CanBeGlobal);
853
854 // Generate the constants for the block literal initializer.
855 llvm::Constant *fields[BlockHeaderSize];
856
857 // isa
858 fields[0] = CGM.getNSConcreteGlobalBlock();
859
860 // __flags
John McCalld16c2cf2011-02-08 08:22:06 +0000861 BlockFlags flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
862 BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
John McCall6b5a61b2011-02-07 10:33:21 +0000863 const llvm::Type *intTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
John McCalld16c2cf2011-02-08 08:22:06 +0000864 fields[1] = llvm::ConstantInt::get(intTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000865
866 // Reserved
867 fields[2] = llvm::Constant::getNullValue(intTy);
868
869 // Function
870 fields[3] = blockFn;
871
872 // Descriptor
873 fields[4] = buildBlockDescriptor(CGM, blockInfo);
874
875 llvm::Constant *init =
876 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
877 /*packed*/ false);
878
879 llvm::GlobalVariable *literal =
880 new llvm::GlobalVariable(CGM.getModule(),
881 init->getType(),
882 /*constant*/ true,
883 llvm::GlobalVariable::InternalLinkage,
884 init,
885 "__block_literal_global");
886 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
887
888 // Return a constant of the appropriately-casted type.
889 const llvm::Type *requiredType =
890 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
891 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000892}
893
Mike Stump00470a12009-03-05 08:32:30 +0000894llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000895CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
896 const CGBlockInfo &blockInfo,
897 const Decl *outerFnDecl,
898 const DeclMapTy &ldm) {
899 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000900
John McCall6b5a61b2011-02-07 10:33:21 +0000901 DebugInfo = CGM.getDebugInfo();
902 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Mike Stump7f28a9c2009-03-13 23:34:28 +0000904 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000905 // to be local to this function as well, in case they're directly
906 // referenced in a block.
907 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
908 const VarDecl *var = dyn_cast<VarDecl>(i->first);
909 if (var && !var->hasLocalStorage())
910 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000911 }
912
John McCall6b5a61b2011-02-07 10:33:21 +0000913 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000914
John McCall6b5a61b2011-02-07 10:33:21 +0000915 // Build the argument list.
916 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000917
John McCall6b5a61b2011-02-07 10:33:21 +0000918 // The first argument is the block pointer. Just take it as a void*
919 // and cast it later.
920 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000921 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 // FIXME: this leaks, and we only need it very temporarily.
924 ImplicitParamDecl *selfDecl =
925 ImplicitParamDecl::Create(getContext(),
926 const_cast<BlockDecl*>(blockDecl),
927 SourceLocation(), II, selfTy);
928 args.push_back(std::make_pair(selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000929
John McCall6b5a61b2011-02-07 10:33:21 +0000930 // Now add the rest of the parameters.
931 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
932 e = blockDecl->param_end(); i != e; ++i)
933 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000934
John McCall6b5a61b2011-02-07 10:33:21 +0000935 // Create the function declaration.
936 const FunctionProtoType *fnType =
937 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
938 const CGFunctionInfo &fnInfo =
939 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
940 fnType->getExtInfo());
941 const llvm::FunctionType *fnLLVMType =
942 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000943
John McCall6b5a61b2011-02-07 10:33:21 +0000944 MangleBuffer name;
945 CGM.getBlockMangledName(GD, name, blockDecl);
946 llvm::Function *fn =
947 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
948 name.getString(), &CGM.getModule());
949 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000950
John McCall6b5a61b2011-02-07 10:33:21 +0000951 // Begin generating the function.
952 StartFunction(blockDecl, fnType->getResultType(), fn, args,
953 blockInfo.getBlockExpr()->getBody()->getLocEnd());
954 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000955
John McCall6b5a61b2011-02-07 10:33:21 +0000956 // Okay. Undo some of what StartFunction did. We really don't need
957 // an alloca for the block address; in theory we could remove it,
958 // but that might do unpleasant things to debug info.
959 llvm::AllocaInst *blockAddrAlloca
960 = cast<llvm::AllocaInst>(LocalDeclMap[selfDecl]);
961 llvm::Value *blockAddr = Builder.CreateLoad(blockAddrAlloca);
962 BlockPointer = Builder.CreateBitCast(blockAddr,
963 blockInfo.StructureType->getPointerTo(),
964 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000965
John McCallea1471e2010-05-20 01:18:31 +0000966 // If we have a C++ 'this' reference, go ahead and force it into
967 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000968 if (blockDecl->capturesCXXThis()) {
969 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
970 blockInfo.CXXThisIndex,
971 "block.captured-this");
972 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000973 }
974
John McCall6b5a61b2011-02-07 10:33:21 +0000975 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
976 // appease it.
977 if (const ObjCMethodDecl *method
978 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
979 const VarDecl *self = method->getSelfDecl();
980
981 // There might not be a capture for 'self', but if there is...
982 if (blockInfo.Captures.count(self)) {
983 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
984 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
985 capture.getIndex(),
986 "block.captured-self");
987 LocalDeclMap[self] = selfAddr;
988 }
989 }
990
991 // Also force all the constant captures.
992 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
993 ce = blockDecl->capture_end(); ci != ce; ++ci) {
994 const VarDecl *variable = ci->getVariable();
995 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
996 if (!capture.isConstant()) continue;
997
998 unsigned align = getContext().getDeclAlign(variable).getQuantity();
999
1000 llvm::AllocaInst *alloca =
1001 CreateMemTemp(variable->getType(), "block.captured-const");
1002 alloca->setAlignment(align);
1003
1004 Builder.CreateStore(capture.getConstant(), alloca, align);
1005
1006 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001007 }
1008
Mike Stumpb289b3f2009-10-01 22:29:41 +00001009 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1010 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1011 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1012 --entry_ptr;
1013
John McCall6b5a61b2011-02-07 10:33:21 +00001014 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001015
Mike Stumpde8c5c72009-10-01 00:27:30 +00001016 // Remember where we were...
1017 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001018
Mike Stumpde8c5c72009-10-01 00:27:30 +00001019 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001020 ++entry_ptr;
1021 Builder.SetInsertPoint(entry, entry_ptr);
1022
John McCall6b5a61b2011-02-07 10:33:21 +00001023 // Emit debug information for all the BlockDeclRefDecls.
1024 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001025 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001026 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1027 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1028 const VarDecl *variable = ci->getVariable();
1029 DI->setLocation(variable->getLocation());
1030
1031 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1032 if (capture.isConstant()) {
1033 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1034 Builder);
1035 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001036 }
John McCall6b5a61b2011-02-07 10:33:21 +00001037
1038 DI->EmitDeclareOfBlockDeclRefVariable(variable, blockAddrAlloca,
1039 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001040 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001041 }
John McCall6b5a61b2011-02-07 10:33:21 +00001042
Mike Stumpde8c5c72009-10-01 00:27:30 +00001043 // And resume where we left off.
1044 if (resume == 0)
1045 Builder.ClearInsertionPoint();
1046 else
1047 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001048
John McCall6b5a61b2011-02-07 10:33:21 +00001049 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001050
John McCall6b5a61b2011-02-07 10:33:21 +00001051 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001052}
Mike Stumpa99038c2009-02-28 09:07:16 +00001053
John McCall6b5a61b2011-02-07 10:33:21 +00001054/*
1055 notes.push_back(HelperInfo());
1056 HelperInfo &note = notes.back();
1057 note.index = capture.getIndex();
1058 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1059 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001060
John McCall6b5a61b2011-02-07 10:33:21 +00001061 if (ci->isByRef()) {
1062 note.flag = BLOCK_FIELD_IS_BYREF;
1063 if (type.isObjCGCWeak())
1064 note.flag |= BLOCK_FIELD_IS_WEAK;
1065 } else if (type->isBlockPointerType()) {
1066 note.flag = BLOCK_FIELD_IS_BLOCK;
1067 } else {
1068 note.flag = BLOCK_FIELD_IS_OBJECT;
1069 }
1070 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001071
Mike Stump00470a12009-03-05 08:32:30 +00001072
Mike Stumpa99038c2009-02-28 09:07:16 +00001073
Mike Stumpdab514f2009-03-04 03:23:46 +00001074
Mike Stumpa4f668f2009-03-06 01:33:24 +00001075
John McCall6b5a61b2011-02-07 10:33:21 +00001076llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001077CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001078 ASTContext &C = getContext();
1079
1080 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001081 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001082 ImplicitParamDecl *dstDecl =
1083 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1084 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1085 ImplicitParamDecl *srcDecl =
1086 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1087 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Mike Stumpa4f668f2009-03-06 01:33:24 +00001089 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001090 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001091
John McCall6b5a61b2011-02-07 10:33:21 +00001092 // FIXME: it would be nice if these were mergeable with things with
1093 // identical semantics.
1094 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001095
1096 llvm::Function *Fn =
1097 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001098 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001099
1100 IdentifierInfo *II
1101 = &CGM.getContext().Idents.get("__copy_helper_block_");
1102
John McCall6b5a61b2011-02-07 10:33:21 +00001103 FunctionDecl *FD = FunctionDecl::Create(C,
1104 C.getTranslationUnitDecl(),
1105 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001106 SC_Static,
1107 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001108 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001109 true);
John McCalld16c2cf2011-02-08 08:22:06 +00001110 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001111
John McCall6b5a61b2011-02-07 10:33:21 +00001112 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001113
John McCalld16c2cf2011-02-08 08:22:06 +00001114 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1115 src = Builder.CreateLoad(src);
1116 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001117
John McCalld16c2cf2011-02-08 08:22:06 +00001118 llvm::Value *dst = GetAddrOfLocalVar(dstDecl);
1119 dst = Builder.CreateLoad(dst);
1120 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001121
John McCall6b5a61b2011-02-07 10:33:21 +00001122 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001123
John McCall6b5a61b2011-02-07 10:33:21 +00001124 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1125 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1126 const VarDecl *variable = ci->getVariable();
1127 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001128
John McCall6b5a61b2011-02-07 10:33:21 +00001129 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1130 if (capture.isConstant()) continue;
1131
1132 const Expr *copyExpr = ci->getCopyExpr();
1133 unsigned flags = 0;
1134
1135 if (copyExpr) {
1136 assert(!ci->isByRef());
1137 // don't bother computing flags
1138 } else if (ci->isByRef()) {
1139 flags = BLOCK_FIELD_IS_BYREF;
1140 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1141 } else if (type->isBlockPointerType()) {
1142 flags = BLOCK_FIELD_IS_BLOCK;
1143 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1144 flags = BLOCK_FIELD_IS_OBJECT;
1145 }
1146
1147 if (!copyExpr && !flags) continue;
1148
1149 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001150 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1151 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001152
1153 // If there's an explicit copy expression, we do that.
1154 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001155 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001156 } else {
1157 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalld16c2cf2011-02-08 08:22:06 +00001158 srcValue = Builder.CreateBitCast(srcValue, Int8PtrTy);
1159 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, Int8PtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001160 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001161 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001162 }
1163 }
1164
John McCalld16c2cf2011-02-08 08:22:06 +00001165 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001166
John McCalld16c2cf2011-02-08 08:22:06 +00001167 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001168}
1169
John McCall6b5a61b2011-02-07 10:33:21 +00001170llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001171CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001172 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001173
John McCall6b5a61b2011-02-07 10:33:21 +00001174 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001175 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001176 ImplicitParamDecl *srcDecl =
1177 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1178 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Mike Stumpa4f668f2009-03-06 01:33:24 +00001180 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001181 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001182
Mike Stump3899a7f2009-06-05 23:26:36 +00001183 // FIXME: We'd like to put these into a mergable by content, with
1184 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001185 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001186
1187 llvm::Function *Fn =
1188 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001189 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001190
1191 IdentifierInfo *II
1192 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1193
John McCall6b5a61b2011-02-07 10:33:21 +00001194 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1195 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001196 SC_Static,
1197 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001198 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001199 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001200
John McCall6b5a61b2011-02-07 10:33:21 +00001201 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001202
John McCalld16c2cf2011-02-08 08:22:06 +00001203 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1204 src = Builder.CreateLoad(src);
1205 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001206
John McCall6b5a61b2011-02-07 10:33:21 +00001207 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1208
John McCalld16c2cf2011-02-08 08:22:06 +00001209 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001210
1211 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1212 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1213 const VarDecl *variable = ci->getVariable();
1214 QualType type = variable->getType();
1215
1216 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1217 if (capture.isConstant()) continue;
1218
John McCalld16c2cf2011-02-08 08:22:06 +00001219 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001220 const CXXDestructorDecl *dtor = 0;
1221
1222 if (ci->isByRef()) {
1223 flags = BLOCK_FIELD_IS_BYREF;
1224 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1225 } else if (type->isBlockPointerType()) {
1226 flags = BLOCK_FIELD_IS_BLOCK;
1227 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1228 flags = BLOCK_FIELD_IS_OBJECT;
1229 } else if (C.getLangOptions().CPlusPlus) {
1230 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1231 if (!record->hasTrivialDestructor())
1232 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001233 }
John McCall6b5a61b2011-02-07 10:33:21 +00001234
John McCalld16c2cf2011-02-08 08:22:06 +00001235 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001236
1237 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001238 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001239
1240 // If there's an explicit copy expression, we do that.
1241 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001242 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001243
1244 // Otherwise we call _Block_object_dispose. It wouldn't be too
1245 // hard to just emit this as a cleanup if we wanted to make sure
1246 // that things were done in reverse.
1247 } else {
1248 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalld16c2cf2011-02-08 08:22:06 +00001249 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001250 BuildBlockRelease(value, flags);
1251 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001252 }
1253
John McCall6b5a61b2011-02-07 10:33:21 +00001254 cleanups.ForceCleanup();
1255
John McCalld16c2cf2011-02-08 08:22:06 +00001256 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001257
John McCalld16c2cf2011-02-08 08:22:06 +00001258 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001259}
1260
John McCalld16c2cf2011-02-08 08:22:06 +00001261llvm::Constant *CodeGenFunction::
1262GeneratebyrefCopyHelperFunction(const llvm::Type *T, BlockFieldFlags flags,
1263 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001264 QualType R = getContext().VoidTy;
1265
1266 FunctionArgList Args;
1267 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001268 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001269 ImplicitParamDecl::Create(getContext(), 0,
1270 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001271 getContext().getPointerType(getContext().VoidTy));
1272 Args.push_back(std::make_pair(Dst, Dst->getType()));
1273
1274 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001275 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001276 ImplicitParamDecl::Create(getContext(), 0,
1277 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001278 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001279 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Mike Stump45031c02009-03-06 02:29:21 +00001281 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001282 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001283
Mike Stump45031c02009-03-06 02:29:21 +00001284 CodeGenTypes &Types = CGM.getTypes();
1285 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1286
Mike Stump3899a7f2009-06-05 23:26:36 +00001287 // FIXME: We'd like to put these into a mergable by content, with
1288 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001289 llvm::Function *Fn =
1290 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001291 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001292
1293 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001294 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001295
1296 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1297 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001298 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001299 SC_Static,
1300 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001301 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001302 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001303
1304 // dst->x
John McCalld16c2cf2011-02-08 08:22:06 +00001305 llvm::Value *V = GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001306 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001307 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001308 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001309 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001310
1311 // src->x
John McCalld16c2cf2011-02-08 08:22:06 +00001312 V = GetAddrOfLocalVar(Src);
Mike Stumpee094222009-03-06 06:12:24 +00001313 V = Builder.CreateLoad(V);
1314 V = Builder.CreateBitCast(V, T);
1315 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001316
John McCalld16c2cf2011-02-08 08:22:06 +00001317 if (Expr *copyExpr = getContext().getBlockVarCopyInits(variable)) {
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001318 llvm::Value *SrcObj = V;
John McCalld16c2cf2011-02-08 08:22:06 +00001319 EmitSynthesizedCXXCopyCtor(DstObj, SrcObj, copyExpr);
1320 } else {
1321 DstObj = Builder.CreateBitCast(DstObj, Int8PtrTy);
1322 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001323 llvm::Value *SrcObj = Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +00001324 flags |= BLOCK_BYREF_CALLER;
1325 llvm::Value *N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001326 llvm::Value *F = CGM.getBlockObjectAssign();
1327 Builder.CreateCall3(F, DstObj, SrcObj, N);
1328 }
1329
John McCalld16c2cf2011-02-08 08:22:06 +00001330 FinishFunction();
Mike Stump45031c02009-03-06 02:29:21 +00001331
John McCalld16c2cf2011-02-08 08:22:06 +00001332 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001333}
1334
Mike Stump1851b682009-03-06 04:53:30 +00001335llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001336CodeGenFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1337 BlockFieldFlags flags,
1338 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001339 QualType R = getContext().VoidTy;
1340
1341 FunctionArgList Args;
1342 // FIXME: This leaks
1343 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001344 ImplicitParamDecl::Create(getContext(), 0,
1345 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001346 getContext().getPointerType(getContext().VoidTy));
1347
1348 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Mike Stump45031c02009-03-06 02:29:21 +00001350 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001351 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001352
Mike Stump45031c02009-03-06 02:29:21 +00001353 CodeGenTypes &Types = CGM.getTypes();
1354 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1355
Mike Stump3899a7f2009-06-05 23:26:36 +00001356 // FIXME: We'd like to put these into a mergable by content, with
1357 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001358 llvm::Function *Fn =
1359 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001360 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001361 &CGM.getModule());
1362
1363 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001364 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001365
1366 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1367 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001368 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001369 SC_Static,
1370 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001371 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001372 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001373
John McCalld16c2cf2011-02-08 08:22:06 +00001374 llvm::Value *V = GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001375 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001376 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001377 V = Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001378
1379 // If it's not any kind of special object, it must have a destructor
1380 // or something.
1381 if (!flags.isSpecialPointer()) {
1382 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
1383 PushDestructorCleanup(variable->getType(), V);
1384 PopCleanupBlocks(CleanupDepth);
1385
1386 // Otherwise, call _Block_object_dispose.
1387 } else {
1388 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001389 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001390
John McCalld16c2cf2011-02-08 08:22:06 +00001391 flags |= BLOCK_BYREF_CALLER;
1392 BuildBlockRelease(V, flags);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001393 }
Mike Stump45031c02009-03-06 02:29:21 +00001394
John McCalld16c2cf2011-02-08 08:22:06 +00001395 FinishFunction();
1396
1397 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001398}
1399
John McCalld16c2cf2011-02-08 08:22:06 +00001400llvm::Constant *CodeGenModule::BuildbyrefCopyHelper(const llvm::Type *T,
1401 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001402 unsigned align,
1403 const VarDecl *var) {
Chris Lattner10976d92009-12-05 08:21:30 +00001404 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001405 // pointer alignment, as we always have at least that much alignment to begin
1406 // with.
John McCalld16c2cf2011-02-08 08:22:06 +00001407 align /= unsigned(getTarget().getPointerAlign(0) / 8);
Chris Lattner10976d92009-12-05 08:21:30 +00001408
Mike Stump3899a7f2009-06-05 23:26:36 +00001409 // As an optimization, we only generate a single function of each kind we
1410 // might need. We need a different one for each alignment and for each
1411 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001412 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1413 llvm::Constant *&Entry = AssignCache[Kind];
1414 if (!Entry)
1415 Entry = CodeGenFunction(*this).
1416 GeneratebyrefCopyHelperFunction(T, flags, var);
1417 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001418}
1419
John McCalld16c2cf2011-02-08 08:22:06 +00001420llvm::Constant *CodeGenModule::BuildbyrefDestroyHelper(const llvm::Type *T,
1421 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001422 unsigned align,
1423 const VarDecl *var) {
Mike Stump3899a7f2009-06-05 23:26:36 +00001424 // All alignments below that of pointer alignment collpase down to just
1425 // pointer alignment, as we always have at least that much alignment to begin
1426 // with.
John McCalld16c2cf2011-02-08 08:22:06 +00001427 align /= unsigned(getTarget().getPointerAlign(0) / 8);
Chris Lattner10976d92009-12-05 08:21:30 +00001428
Mike Stump3899a7f2009-06-05 23:26:36 +00001429 // As an optimization, we only generate a single function of each kind we
1430 // might need. We need a different one for each alignment and for each
1431 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001432 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1433 llvm::Constant *&Entry = DestroyCache[Kind];
1434 if (!Entry)
1435 Entry = CodeGenFunction(*this).
1436 GeneratebyrefDestroyHelperFunction(T, flags, var);
1437 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001438}
1439
John McCalld16c2cf2011-02-08 08:22:06 +00001440void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001441 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001442 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001443 V = Builder.CreateBitCast(V, Int8PtrTy);
1444 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001445 Builder.CreateCall2(F, V, N);
1446}