blob: fb90e025eb7ed1da9917dcaffd769ac09db01d16 [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
John McCall5936e332011-02-15 09:22:45 +0000484 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
485 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000486 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 McCall5936e332011-02-15 09:22:45 +0000520 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
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 McCall5936e332011-02-15 09:22:45 +0000529 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
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()) {
John McCall5936e332011-02-15 09:22:45 +0000607 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000608 if (ci->isNested())
609 src = Builder.CreateLoad(src, "byref.capture");
610 else
John McCall5936e332011-02-15 09:22:45 +0000611 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000612
John McCall5936e332011-02-15 09:22:45 +0000613 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000614 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 Stump9b8a7972009-02-13 15:25:34 +0000713 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000714 // void *__isa;
715 // int __flags;
716 // int __reserved;
717 // void (*__invoke)(void *);
718 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000719 // };
John McCall5936e332011-02-15 09:22:45 +0000720 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
721 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000722 IntTy,
723 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000724 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000725 BlockDescPtrTy,
726 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000727
Mike Stump9b8a7972009-02-13 15:25:34 +0000728 getModule().addTypeName("struct.__block_literal_generic",
729 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000730
Mike Stump9b8a7972009-02-13 15:25:34 +0000731 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000732}
733
Mike Stumpbd65cac2009-02-19 01:01:04 +0000734
Anders Carlssona1736c02009-12-24 21:13:40 +0000735RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
736 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000737 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000738 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000739
Anders Carlssonacfde802009-02-12 00:39:25 +0000740 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
741
742 // Get a pointer to the generic block literal.
743 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000744 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000745
746 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000747 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000748 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
749
750 // Get the function pointer from the literal.
751 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000752
John McCall5936e332011-02-15 09:22:45 +0000753 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000754
Anders Carlssonacfde802009-02-12 00:39:25 +0000755 // Add the block literal.
756 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
757 CallArgList Args;
758 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000759
Anders Carlsson782f3972009-04-08 23:13:16 +0000760 QualType FnType = BPT->getPointeeType();
761
Anders Carlssonacfde802009-02-12 00:39:25 +0000762 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000763 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000764 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000765
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000766 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000767 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000768
John McCall04a67a62010-02-05 21:31:56 +0000769 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
770 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000771
Mike Stump1eb44332009-09-09 15:08:12 +0000772 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000773 CGM.getTypes().getFunctionInfo(ResultType, Args,
774 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000776 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000777 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000778 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Owen Anderson96e0fc72009-07-29 22:16:19 +0000780 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000781 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Anders Carlssonacfde802009-02-12 00:39:25 +0000783 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000784 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000785}
Anders Carlssond5cab542009-02-12 17:55:02 +0000786
John McCall6b5a61b2011-02-07 10:33:21 +0000787llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
788 bool isByRef) {
789 assert(BlockInfo && "evaluating block ref without block information?");
790 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000791
John McCall6b5a61b2011-02-07 10:33:21 +0000792 // Handle constant captures.
793 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 llvm::Value *addr =
796 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
797 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000798
John McCall6b5a61b2011-02-07 10:33:21 +0000799 if (isByRef) {
800 // addr should be a void** right now. Load, then cast the result
801 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000802
John McCall6b5a61b2011-02-07 10:33:21 +0000803 addr = Builder.CreateLoad(addr);
804 const llvm::PointerType *byrefPointerType
805 = llvm::PointerType::get(BuildByRefType(variable), 0);
806 addr = Builder.CreateBitCast(addr, byrefPointerType,
807 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000808
John McCall6b5a61b2011-02-07 10:33:21 +0000809 // Follow the forwarding pointer.
810 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
811 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000812
John McCall6b5a61b2011-02-07 10:33:21 +0000813 // Cast back to byref* and GEP over to the actual object.
814 addr = Builder.CreateBitCast(addr, byrefPointerType);
815 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
816 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000817 }
818
John McCall6b5a61b2011-02-07 10:33:21 +0000819 if (variable->getType()->isReferenceType())
820 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000821
John McCall6b5a61b2011-02-07 10:33:21 +0000822 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000823}
824
Mike Stump67a64482009-02-14 22:16:35 +0000825llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000826CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000827 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000828 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000829
John McCall6b5a61b2011-02-07 10:33:21 +0000830 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000831 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000832
John McCall6b5a61b2011-02-07 10:33:21 +0000833 // Using that metadata, generate the actual block function.
834 llvm::Constant *blockFn;
835 {
836 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000837 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
838 blockInfo,
839 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000840 }
John McCall5936e332011-02-15 09:22:45 +0000841 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000842
John McCalld16c2cf2011-02-08 08:22:06 +0000843 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000844}
845
John McCall6b5a61b2011-02-07 10:33:21 +0000846static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
847 const CGBlockInfo &blockInfo,
848 llvm::Constant *blockFn) {
849 assert(blockInfo.CanBeGlobal);
850
851 // Generate the constants for the block literal initializer.
852 llvm::Constant *fields[BlockHeaderSize];
853
854 // isa
855 fields[0] = CGM.getNSConcreteGlobalBlock();
856
857 // __flags
John McCalld16c2cf2011-02-08 08:22:06 +0000858 BlockFlags flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
859 BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
John McCall5936e332011-02-15 09:22:45 +0000860 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000861
862 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000863 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000864
865 // Function
866 fields[3] = blockFn;
867
868 // Descriptor
869 fields[4] = buildBlockDescriptor(CGM, blockInfo);
870
871 llvm::Constant *init =
872 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
873 /*packed*/ false);
874
875 llvm::GlobalVariable *literal =
876 new llvm::GlobalVariable(CGM.getModule(),
877 init->getType(),
878 /*constant*/ true,
879 llvm::GlobalVariable::InternalLinkage,
880 init,
881 "__block_literal_global");
882 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
883
884 // Return a constant of the appropriately-casted type.
885 const llvm::Type *requiredType =
886 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
887 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000888}
889
Mike Stump00470a12009-03-05 08:32:30 +0000890llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000891CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
892 const CGBlockInfo &blockInfo,
893 const Decl *outerFnDecl,
894 const DeclMapTy &ldm) {
895 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000896
John McCall6b5a61b2011-02-07 10:33:21 +0000897 DebugInfo = CGM.getDebugInfo();
898 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Mike Stump7f28a9c2009-03-13 23:34:28 +0000900 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000901 // to be local to this function as well, in case they're directly
902 // referenced in a block.
903 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
904 const VarDecl *var = dyn_cast<VarDecl>(i->first);
905 if (var && !var->hasLocalStorage())
906 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000907 }
908
John McCall6b5a61b2011-02-07 10:33:21 +0000909 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911 // Build the argument list.
912 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 // The first argument is the block pointer. Just take it as a void*
915 // and cast it later.
916 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000917 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000918
John McCall6b5a61b2011-02-07 10:33:21 +0000919 // FIXME: this leaks, and we only need it very temporarily.
920 ImplicitParamDecl *selfDecl =
921 ImplicitParamDecl::Create(getContext(),
922 const_cast<BlockDecl*>(blockDecl),
923 SourceLocation(), II, selfTy);
924 args.push_back(std::make_pair(selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000925
John McCall6b5a61b2011-02-07 10:33:21 +0000926 // Now add the rest of the parameters.
927 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
928 e = blockDecl->param_end(); i != e; ++i)
929 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000930
John McCall6b5a61b2011-02-07 10:33:21 +0000931 // Create the function declaration.
932 const FunctionProtoType *fnType =
933 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
934 const CGFunctionInfo &fnInfo =
935 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
936 fnType->getExtInfo());
937 const llvm::FunctionType *fnLLVMType =
938 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000939
John McCall6b5a61b2011-02-07 10:33:21 +0000940 MangleBuffer name;
941 CGM.getBlockMangledName(GD, name, blockDecl);
942 llvm::Function *fn =
943 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
944 name.getString(), &CGM.getModule());
945 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000946
John McCall6b5a61b2011-02-07 10:33:21 +0000947 // Begin generating the function.
948 StartFunction(blockDecl, fnType->getResultType(), fn, args,
949 blockInfo.getBlockExpr()->getBody()->getLocEnd());
950 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000951
John McCall6b5a61b2011-02-07 10:33:21 +0000952 // Okay. Undo some of what StartFunction did. We really don't need
953 // an alloca for the block address; in theory we could remove it,
954 // but that might do unpleasant things to debug info.
955 llvm::AllocaInst *blockAddrAlloca
956 = cast<llvm::AllocaInst>(LocalDeclMap[selfDecl]);
957 llvm::Value *blockAddr = Builder.CreateLoad(blockAddrAlloca);
958 BlockPointer = Builder.CreateBitCast(blockAddr,
959 blockInfo.StructureType->getPointerTo(),
960 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000961
John McCallea1471e2010-05-20 01:18:31 +0000962 // If we have a C++ 'this' reference, go ahead and force it into
963 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000964 if (blockDecl->capturesCXXThis()) {
965 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
966 blockInfo.CXXThisIndex,
967 "block.captured-this");
968 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000969 }
970
John McCall6b5a61b2011-02-07 10:33:21 +0000971 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
972 // appease it.
973 if (const ObjCMethodDecl *method
974 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
975 const VarDecl *self = method->getSelfDecl();
976
977 // There might not be a capture for 'self', but if there is...
978 if (blockInfo.Captures.count(self)) {
979 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
980 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
981 capture.getIndex(),
982 "block.captured-self");
983 LocalDeclMap[self] = selfAddr;
984 }
985 }
986
987 // Also force all the constant captures.
988 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
989 ce = blockDecl->capture_end(); ci != ce; ++ci) {
990 const VarDecl *variable = ci->getVariable();
991 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
992 if (!capture.isConstant()) continue;
993
994 unsigned align = getContext().getDeclAlign(variable).getQuantity();
995
996 llvm::AllocaInst *alloca =
997 CreateMemTemp(variable->getType(), "block.captured-const");
998 alloca->setAlignment(align);
999
1000 Builder.CreateStore(capture.getConstant(), alloca, align);
1001
1002 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001003 }
1004
Mike Stumpb289b3f2009-10-01 22:29:41 +00001005 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1006 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1007 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1008 --entry_ptr;
1009
John McCall6b5a61b2011-02-07 10:33:21 +00001010 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001011
Mike Stumpde8c5c72009-10-01 00:27:30 +00001012 // Remember where we were...
1013 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001014
Mike Stumpde8c5c72009-10-01 00:27:30 +00001015 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001016 ++entry_ptr;
1017 Builder.SetInsertPoint(entry, entry_ptr);
1018
John McCall6b5a61b2011-02-07 10:33:21 +00001019 // Emit debug information for all the BlockDeclRefDecls.
1020 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001021 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001022 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1023 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1024 const VarDecl *variable = ci->getVariable();
1025 DI->setLocation(variable->getLocation());
1026
1027 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1028 if (capture.isConstant()) {
1029 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1030 Builder);
1031 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001032 }
John McCall6b5a61b2011-02-07 10:33:21 +00001033
1034 DI->EmitDeclareOfBlockDeclRefVariable(variable, blockAddrAlloca,
1035 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001036 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001037 }
John McCall6b5a61b2011-02-07 10:33:21 +00001038
Mike Stumpde8c5c72009-10-01 00:27:30 +00001039 // And resume where we left off.
1040 if (resume == 0)
1041 Builder.ClearInsertionPoint();
1042 else
1043 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001044
John McCall6b5a61b2011-02-07 10:33:21 +00001045 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001046
John McCall6b5a61b2011-02-07 10:33:21 +00001047 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001048}
Mike Stumpa99038c2009-02-28 09:07:16 +00001049
John McCall6b5a61b2011-02-07 10:33:21 +00001050/*
1051 notes.push_back(HelperInfo());
1052 HelperInfo &note = notes.back();
1053 note.index = capture.getIndex();
1054 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1055 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001056
John McCall6b5a61b2011-02-07 10:33:21 +00001057 if (ci->isByRef()) {
1058 note.flag = BLOCK_FIELD_IS_BYREF;
1059 if (type.isObjCGCWeak())
1060 note.flag |= BLOCK_FIELD_IS_WEAK;
1061 } else if (type->isBlockPointerType()) {
1062 note.flag = BLOCK_FIELD_IS_BLOCK;
1063 } else {
1064 note.flag = BLOCK_FIELD_IS_OBJECT;
1065 }
1066 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001067
Mike Stump00470a12009-03-05 08:32:30 +00001068
Mike Stumpa99038c2009-02-28 09:07:16 +00001069
Mike Stumpdab514f2009-03-04 03:23:46 +00001070
Mike Stumpa4f668f2009-03-06 01:33:24 +00001071
John McCall6b5a61b2011-02-07 10:33:21 +00001072llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001073CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001074 ASTContext &C = getContext();
1075
1076 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001077 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001078 ImplicitParamDecl *dstDecl =
1079 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1080 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1081 ImplicitParamDecl *srcDecl =
1082 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1083 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Mike Stumpa4f668f2009-03-06 01:33:24 +00001085 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001086 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001087
John McCall6b5a61b2011-02-07 10:33:21 +00001088 // FIXME: it would be nice if these were mergeable with things with
1089 // identical semantics.
1090 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001091
1092 llvm::Function *Fn =
1093 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001094 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001095
1096 IdentifierInfo *II
1097 = &CGM.getContext().Idents.get("__copy_helper_block_");
1098
John McCall6b5a61b2011-02-07 10:33:21 +00001099 FunctionDecl *FD = FunctionDecl::Create(C,
1100 C.getTranslationUnitDecl(),
1101 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001102 SC_Static,
1103 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001104 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001105 true);
John McCalld16c2cf2011-02-08 08:22:06 +00001106 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001107
John McCall6b5a61b2011-02-07 10:33:21 +00001108 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001109
John McCalld16c2cf2011-02-08 08:22:06 +00001110 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1111 src = Builder.CreateLoad(src);
1112 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001113
John McCalld16c2cf2011-02-08 08:22:06 +00001114 llvm::Value *dst = GetAddrOfLocalVar(dstDecl);
1115 dst = Builder.CreateLoad(dst);
1116 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001117
John McCall6b5a61b2011-02-07 10:33:21 +00001118 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001119
John McCall6b5a61b2011-02-07 10:33:21 +00001120 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1121 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1122 const VarDecl *variable = ci->getVariable();
1123 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1126 if (capture.isConstant()) continue;
1127
1128 const Expr *copyExpr = ci->getCopyExpr();
1129 unsigned flags = 0;
1130
1131 if (copyExpr) {
1132 assert(!ci->isByRef());
1133 // don't bother computing flags
1134 } else if (ci->isByRef()) {
1135 flags = BLOCK_FIELD_IS_BYREF;
1136 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1137 } else if (type->isBlockPointerType()) {
1138 flags = BLOCK_FIELD_IS_BLOCK;
1139 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1140 flags = BLOCK_FIELD_IS_OBJECT;
1141 }
1142
1143 if (!copyExpr && !flags) continue;
1144
1145 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001146 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1147 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001148
1149 // If there's an explicit copy expression, we do that.
1150 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001151 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001152 } else {
1153 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001154 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1155 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001156 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001157 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001158 }
1159 }
1160
John McCalld16c2cf2011-02-08 08:22:06 +00001161 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001162
John McCall5936e332011-02-15 09:22:45 +00001163 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001164}
1165
John McCall6b5a61b2011-02-07 10:33:21 +00001166llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001167CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001168 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001169
John McCall6b5a61b2011-02-07 10:33:21 +00001170 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001171 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001172 ImplicitParamDecl *srcDecl =
1173 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1174 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Mike Stumpa4f668f2009-03-06 01:33:24 +00001176 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001177 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001178
Mike Stump3899a7f2009-06-05 23:26:36 +00001179 // FIXME: We'd like to put these into a mergable by content, with
1180 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001181 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001182
1183 llvm::Function *Fn =
1184 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001185 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001186
1187 IdentifierInfo *II
1188 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1189
John McCall6b5a61b2011-02-07 10:33:21 +00001190 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1191 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001192 SC_Static,
1193 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001194 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001195 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001196
John McCall6b5a61b2011-02-07 10:33:21 +00001197 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001198
John McCalld16c2cf2011-02-08 08:22:06 +00001199 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1200 src = Builder.CreateLoad(src);
1201 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001202
John McCall6b5a61b2011-02-07 10:33:21 +00001203 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1204
John McCalld16c2cf2011-02-08 08:22:06 +00001205 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001206
1207 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1208 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1209 const VarDecl *variable = ci->getVariable();
1210 QualType type = variable->getType();
1211
1212 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1213 if (capture.isConstant()) continue;
1214
John McCalld16c2cf2011-02-08 08:22:06 +00001215 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001216 const CXXDestructorDecl *dtor = 0;
1217
1218 if (ci->isByRef()) {
1219 flags = BLOCK_FIELD_IS_BYREF;
1220 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1221 } else if (type->isBlockPointerType()) {
1222 flags = BLOCK_FIELD_IS_BLOCK;
1223 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1224 flags = BLOCK_FIELD_IS_OBJECT;
1225 } else if (C.getLangOptions().CPlusPlus) {
1226 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1227 if (!record->hasTrivialDestructor())
1228 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001229 }
John McCall6b5a61b2011-02-07 10:33:21 +00001230
John McCalld16c2cf2011-02-08 08:22:06 +00001231 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001232
1233 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001234 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001235
1236 // If there's an explicit copy expression, we do that.
1237 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001238 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001239
1240 // Otherwise we call _Block_object_dispose. It wouldn't be too
1241 // hard to just emit this as a cleanup if we wanted to make sure
1242 // that things were done in reverse.
1243 } else {
1244 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001245 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001246 BuildBlockRelease(value, flags);
1247 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001248 }
1249
John McCall6b5a61b2011-02-07 10:33:21 +00001250 cleanups.ForceCleanup();
1251
John McCalld16c2cf2011-02-08 08:22:06 +00001252 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001253
John McCall5936e332011-02-15 09:22:45 +00001254 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001255}
1256
John McCalld16c2cf2011-02-08 08:22:06 +00001257llvm::Constant *CodeGenFunction::
1258GeneratebyrefCopyHelperFunction(const llvm::Type *T, BlockFieldFlags flags,
1259 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001260 QualType R = getContext().VoidTy;
1261
1262 FunctionArgList Args;
1263 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001264 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001265 ImplicitParamDecl::Create(getContext(), 0,
1266 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001267 getContext().getPointerType(getContext().VoidTy));
1268 Args.push_back(std::make_pair(Dst, Dst->getType()));
1269
1270 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001271 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001272 ImplicitParamDecl::Create(getContext(), 0,
1273 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001274 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001275 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Mike Stump45031c02009-03-06 02:29:21 +00001277 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001278 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001279
Mike Stump45031c02009-03-06 02:29:21 +00001280 CodeGenTypes &Types = CGM.getTypes();
1281 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1282
Mike Stump3899a7f2009-06-05 23:26:36 +00001283 // FIXME: We'd like to put these into a mergable by content, with
1284 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001285 llvm::Function *Fn =
1286 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001287 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001288
1289 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001290 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001291
1292 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1293 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001294 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001295 SC_Static,
1296 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001297 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001298 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001299
1300 // dst->x
John McCalld16c2cf2011-02-08 08:22:06 +00001301 llvm::Value *V = GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001302 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001303 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001304 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001305 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001306
1307 // src->x
John McCalld16c2cf2011-02-08 08:22:06 +00001308 V = GetAddrOfLocalVar(Src);
Mike Stumpee094222009-03-06 06:12:24 +00001309 V = Builder.CreateLoad(V);
1310 V = Builder.CreateBitCast(V, T);
1311 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001312
John McCalld16c2cf2011-02-08 08:22:06 +00001313 if (Expr *copyExpr = getContext().getBlockVarCopyInits(variable)) {
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001314 llvm::Value *SrcObj = V;
John McCalld16c2cf2011-02-08 08:22:06 +00001315 EmitSynthesizedCXXCopyCtor(DstObj, SrcObj, copyExpr);
1316 } else {
John McCall5936e332011-02-15 09:22:45 +00001317 DstObj = Builder.CreateBitCast(DstObj, VoidPtrTy);
1318 V = Builder.CreateBitCast(V, VoidPtrPtrTy);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001319 llvm::Value *SrcObj = Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +00001320 flags |= BLOCK_BYREF_CALLER;
1321 llvm::Value *N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001322 llvm::Value *F = CGM.getBlockObjectAssign();
1323 Builder.CreateCall3(F, DstObj, SrcObj, N);
1324 }
1325
John McCalld16c2cf2011-02-08 08:22:06 +00001326 FinishFunction();
Mike Stump45031c02009-03-06 02:29:21 +00001327
John McCalld16c2cf2011-02-08 08:22:06 +00001328 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001329}
1330
Mike Stump1851b682009-03-06 04:53:30 +00001331llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001332CodeGenFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1333 BlockFieldFlags flags,
1334 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001335 QualType R = getContext().VoidTy;
1336
1337 FunctionArgList Args;
1338 // FIXME: This leaks
1339 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001340 ImplicitParamDecl::Create(getContext(), 0,
1341 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001342 getContext().getPointerType(getContext().VoidTy));
1343
1344 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Mike Stump45031c02009-03-06 02:29:21 +00001346 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001347 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001348
Mike Stump45031c02009-03-06 02:29:21 +00001349 CodeGenTypes &Types = CGM.getTypes();
1350 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1351
Mike Stump3899a7f2009-06-05 23:26:36 +00001352 // FIXME: We'd like to put these into a mergable by content, with
1353 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001354 llvm::Function *Fn =
1355 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001356 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001357 &CGM.getModule());
1358
1359 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001360 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001361
1362 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1363 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001364 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001365 SC_Static,
1366 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001367 false, true);
John McCalld16c2cf2011-02-08 08:22:06 +00001368 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001369
John McCalld16c2cf2011-02-08 08:22:06 +00001370 llvm::Value *V = GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001371 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001372 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001373 V = Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001374
1375 // If it's not any kind of special object, it must have a destructor
1376 // or something.
1377 if (!flags.isSpecialPointer()) {
1378 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
1379 PushDestructorCleanup(variable->getType(), V);
1380 PopCleanupBlocks(CleanupDepth);
1381
1382 // Otherwise, call _Block_object_dispose.
1383 } else {
1384 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001385 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001386
John McCalld16c2cf2011-02-08 08:22:06 +00001387 flags |= BLOCK_BYREF_CALLER;
1388 BuildBlockRelease(V, flags);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001389 }
Mike Stump45031c02009-03-06 02:29:21 +00001390
John McCalld16c2cf2011-02-08 08:22:06 +00001391 FinishFunction();
1392
1393 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001394}
1395
John McCalld16c2cf2011-02-08 08:22:06 +00001396llvm::Constant *CodeGenModule::BuildbyrefCopyHelper(const llvm::Type *T,
1397 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001398 unsigned align,
1399 const VarDecl *var) {
Chris Lattner10976d92009-12-05 08:21:30 +00001400 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001401 // pointer alignment, as we always have at least that much alignment to begin
1402 // with.
John McCalld16c2cf2011-02-08 08:22:06 +00001403 align /= unsigned(getTarget().getPointerAlign(0) / 8);
Chris Lattner10976d92009-12-05 08:21:30 +00001404
Mike Stump3899a7f2009-06-05 23:26:36 +00001405 // As an optimization, we only generate a single function of each kind we
1406 // might need. We need a different one for each alignment and for each
1407 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001408 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1409 llvm::Constant *&Entry = AssignCache[Kind];
1410 if (!Entry)
1411 Entry = CodeGenFunction(*this).
1412 GeneratebyrefCopyHelperFunction(T, flags, var);
1413 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001414}
1415
John McCalld16c2cf2011-02-08 08:22:06 +00001416llvm::Constant *CodeGenModule::BuildbyrefDestroyHelper(const llvm::Type *T,
1417 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001418 unsigned align,
1419 const VarDecl *var) {
Mike Stump3899a7f2009-06-05 23:26:36 +00001420 // All alignments below that of pointer alignment collpase down to just
1421 // pointer alignment, as we always have at least that much alignment to begin
1422 // with.
John McCalld16c2cf2011-02-08 08:22:06 +00001423 align /= unsigned(getTarget().getPointerAlign(0) / 8);
Chris Lattner10976d92009-12-05 08:21:30 +00001424
Mike Stump3899a7f2009-06-05 23:26:36 +00001425 // As an optimization, we only generate a single function of each kind we
1426 // might need. We need a different one for each alignment and for each
1427 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001428 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1429 llvm::Constant *&Entry = DestroyCache[Kind];
1430 if (!Entry)
1431 Entry = CodeGenFunction(*this).
1432 GeneratebyrefDestroyHelperFunction(T, flags, var);
1433 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001434}
1435
John McCalld16c2cf2011-02-08 08:22:06 +00001436void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001437 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001438 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001439 V = Builder.CreateBitCast(V, Int8PtrTy);
1440 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001441 Builder.CreateCall2(F, V, N);
1442}