blob: 68bc8b7d3559b6d4e3da060692f1c160eb81f187 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall6b5a61b2011-02-07 10:33:21 +000028CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCallc20e2042011-02-16 00:49:34 +000030 HasCXXObject(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000031
32 // Skip asm prefix, if any.
33 if (Name && Name[0] == '\01')
34 ++Name;
35}
36
John McCall6b5a61b2011-02-07 10:33:21 +000037/// Build the given block as a global block.
38static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
39 const CGBlockInfo &blockInfo,
40 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000041
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the helper function to copy a block.
43static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo) {
45 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
46}
47
48/// Build the helper function to dipose of a block.
49static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
50 const CGBlockInfo &blockInfo) {
51 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
52}
53
54/// Build the block descriptor constant for a block.
55static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
56 const CGBlockInfo &blockInfo) {
57 ASTContext &C = CGM.getContext();
58
59 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
60 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
61
62 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000063
64 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000065 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000068 // FIXME: What is the right way to say this doesn't fit? We should give
69 // a user diagnostic in that case. Better fix would be to change the
70 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000071 elements.push_back(llvm::ConstantInt::get(ulong,
72 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000073
John McCall6b5a61b2011-02-07 10:33:21 +000074 // Optional copy/dispose helpers.
75 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000076 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000077 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000078
79 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081 }
82
John McCall6b5a61b2011-02-07 10:33:21 +000083 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
84 std::string typeAtEncoding =
85 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
86 elements.push_back(llvm::ConstantExpr::getBitCast(
87 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000088
John McCall6b5a61b2011-02-07 10:33:21 +000089 // GC layout.
90 if (C.getLangOptions().ObjC1)
91 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
92 else
93 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000094
John McCall6b5a61b2011-02-07 10:33:21 +000095 llvm::Constant *init =
96 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
97 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +000098
John McCall6b5a61b2011-02-07 10:33:21 +000099 llvm::GlobalVariable *global =
100 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
101 llvm::GlobalValue::InternalLinkage,
102 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000103
John McCall6b5a61b2011-02-07 10:33:21 +0000104 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000105}
106
John McCalld16c2cf2011-02-08 08:22:06 +0000107static BlockFlags computeBlockFlag(CodeGenModule &CGM,
108 const BlockExpr *BE,
109 BlockFlags flags) {
110 const FunctionType *ftype = BE->getFunctionType();
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000111
John McCalld16c2cf2011-02-08 08:22:06 +0000112 // This is a bit overboard.
113 CallArgList args;
114 const CGFunctionInfo &fnInfo =
115 CGM.getTypes().getFunctionInfo(ftype->getResultType(), args,
116 ftype->getExtInfo());
117
118 if (CGM.ReturnTypeUsesSRet(fnInfo))
119 flags |= BLOCK_USE_STRET;
120
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000121 return flags;
122}
123
John McCall6b5a61b2011-02-07 10:33:21 +0000124/*
125 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000126
John McCall6b5a61b2011-02-07 10:33:21 +0000127 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
128 struct Block_literal {
129 /// Initialized to one of:
130 /// extern void *_NSConcreteStackBlock[];
131 /// extern void *_NSConcreteGlobalBlock[];
132 ///
133 /// In theory, we could start one off malloc'ed by setting
134 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
135 /// this isa:
136 /// extern void *_NSConcreteMallocBlock[];
137 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000138
John McCall6b5a61b2011-02-07 10:33:21 +0000139 /// These are the flags (with corresponding bit number) that the
140 /// compiler is actually supposed to know about.
141 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
142 /// descriptor provides copy and dispose helper functions
143 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
144 /// object with a nontrivial destructor or copy constructor
145 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
146 /// as global memory
147 /// 29. BLOCK_USE_STRET - indicates that the block function
148 /// uses stret, which objc_msgSend needs to know about
149 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
150 /// @encoded signature string
151 /// And we're not supposed to manipulate these:
152 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
153 /// to malloc'ed memory
154 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
155 /// to GC-allocated memory
156 /// Additionally, the bottom 16 bits are a reference count which
157 /// should be zero on the stack.
158 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160 /// Reserved; should be zero-initialized.
161 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Function pointer generated from block literal.
164 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Block description metadata generated from block literal.
167 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Captured values follow.
170 _CapturesTypes captures...;
171 };
172 */
David Chisnall5e530af2009-11-17 19:33:30 +0000173
John McCall6b5a61b2011-02-07 10:33:21 +0000174/// The number of fields in a block header.
175const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000176
John McCall6b5a61b2011-02-07 10:33:21 +0000177namespace {
178 /// A chunk of data that we actually have to capture in the block.
179 struct BlockLayoutChunk {
180 CharUnits Alignment;
181 CharUnits Size;
182 const BlockDecl::Capture *Capture; // null for 'this'
183 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000184
John McCall6b5a61b2011-02-07 10:33:21 +0000185 BlockLayoutChunk(CharUnits align, CharUnits size,
186 const BlockDecl::Capture *capture,
187 const llvm::Type *type)
188 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
John McCall6b5a61b2011-02-07 10:33:21 +0000190 /// Tell the block info that this chunk has the given field index.
191 void setIndex(CGBlockInfo &info, unsigned index) {
192 if (!Capture)
193 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000194 else
John McCall6b5a61b2011-02-07 10:33:21 +0000195 info.Captures[Capture->getVariable()]
196 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000197 }
John McCall6b5a61b2011-02-07 10:33:21 +0000198 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000199
John McCall6b5a61b2011-02-07 10:33:21 +0000200 /// Order by descending alignment.
201 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
202 return left.Alignment > right.Alignment;
203 }
204}
205
John McCall461c9c12011-02-08 03:07:00 +0000206/// Determines if the given record type has a mutable field.
207static bool hasMutableField(const CXXRecordDecl *record) {
208 for (CXXRecordDecl::field_iterator
209 i = record->field_begin(), e = record->field_end(); i != e; ++i)
210 if ((*i)->isMutable())
211 return true;
212
213 for (CXXRecordDecl::base_class_const_iterator
214 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
215 const RecordType *record = i->getType()->castAs<RecordType>();
216 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
217 return true;
218 }
219
220 return false;
221}
222
223/// Determines if the given type is safe for constant capture in C++.
224static bool isSafeForCXXConstantCapture(QualType type) {
225 const RecordType *recordType =
226 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
227
228 // Only records can be unsafe.
229 if (!recordType) return true;
230
231 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
232
233 // Maintain semantics for classes with non-trivial dtors or copy ctors.
234 if (!record->hasTrivialDestructor()) return false;
235 if (!record->hasTrivialCopyConstructor()) return false;
236
237 // Otherwise, we just have to make sure there aren't any mutable
238 // fields that might have changed since initialization.
239 return !hasMutableField(record);
240}
241
John McCall6b5a61b2011-02-07 10:33:21 +0000242/// It is illegal to modify a const object after initialization.
243/// Therefore, if a const object has a constant initializer, we don't
244/// actually need to keep storage for it in the block; we'll just
245/// rematerialize it at the start of the block function. This is
246/// acceptable because we make no promises about address stability of
247/// captured variables.
248static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
249 const VarDecl *var) {
250 QualType type = var->getType();
251
252 // We can only do this if the variable is const.
253 if (!type.isConstQualified()) return 0;
254
John McCall461c9c12011-02-08 03:07:00 +0000255 // Furthermore, in C++ we have to worry about mutable fields:
256 // C++ [dcl.type.cv]p4:
257 // Except that any class member declared mutable can be
258 // modified, any attempt to modify a const object during its
259 // lifetime results in undefined behavior.
260 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000261 return 0;
262
263 // If the variable doesn't have any initializer (shouldn't this be
264 // invalid?), it's not clear what we should do. Maybe capture as
265 // zero?
266 const Expr *init = var->getInit();
267 if (!init) return 0;
268
269 return CGM.EmitConstantExpr(init, var->getType());
270}
271
272/// Get the low bit of a nonzero character count. This is the
273/// alignment of the nth byte if the 0th byte is universally aligned.
274static CharUnits getLowBit(CharUnits v) {
275 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
276}
277
278static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
279 std::vector<const llvm::Type*> &elementTypes) {
280 ASTContext &C = CGM.getContext();
281
282 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
283 CharUnits ptrSize, ptrAlign, intSize, intAlign;
284 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
285 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
286
287 // Are there crazy embedded platforms where this isn't true?
288 assert(intSize <= ptrSize && "layout assumptions horribly violated");
289
290 CharUnits headerSize = ptrSize;
291 if (2 * intSize < ptrAlign) headerSize += ptrSize;
292 else headerSize += 2 * intSize;
293 headerSize += 2 * ptrSize;
294
295 info.BlockAlign = ptrAlign;
296 info.BlockSize = headerSize;
297
298 assert(elementTypes.empty());
299 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
300 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
301 elementTypes.push_back(i8p);
302 elementTypes.push_back(intTy);
303 elementTypes.push_back(intTy);
304 elementTypes.push_back(i8p);
305 elementTypes.push_back(CGM.getBlockDescriptorType());
306
307 assert(elementTypes.size() == BlockHeaderSize);
308}
309
310/// Compute the layout of the given block. Attempts to lay the block
311/// out with minimal space requirements.
312static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
313 ASTContext &C = CGM.getContext();
314 const BlockDecl *block = info.getBlockDecl();
315
316 std::vector<const llvm::Type*> elementTypes;
317 initializeForBlockHeader(CGM, info, elementTypes);
318
319 if (!block->hasCaptures()) {
320 info.StructureType =
321 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
322 info.CanBeGlobal = true;
323 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000324 }
Mike Stump00470a12009-03-05 08:32:30 +0000325
John McCall6b5a61b2011-02-07 10:33:21 +0000326 // Collect the layout chunks.
327 llvm::SmallVector<BlockLayoutChunk, 16> layout;
328 layout.reserve(block->capturesCXXThis() +
329 (block->capture_end() - block->capture_begin()));
330
331 CharUnits maxFieldAlign;
332
333 // First, 'this'.
334 if (block->capturesCXXThis()) {
335 const DeclContext *DC = block->getDeclContext();
336 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
337 ;
338 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
339
340 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
341 std::pair<CharUnits,CharUnits> tinfo
342 = CGM.getContext().getTypeInfoInChars(thisType);
343 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
344
345 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
346 }
347
348 // Next, all the block captures.
349 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
350 ce = block->capture_end(); ci != ce; ++ci) {
351 const VarDecl *variable = ci->getVariable();
352
353 if (ci->isByRef()) {
354 // We have to copy/dispose of the __block reference.
355 info.NeedsCopyDispose = true;
356
John McCall6b5a61b2011-02-07 10:33:21 +0000357 // Just use void* instead of a pointer to the byref type.
358 QualType byRefPtrTy = C.VoidPtrTy;
359
360 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
361 std::pair<CharUnits,CharUnits> tinfo
362 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
363 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
364
365 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
366 &*ci, llvmType));
367 continue;
368 }
369
370 // Otherwise, build a layout chunk with the size and alignment of
371 // the declaration.
372 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
373 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
374 continue;
375 }
376
377 // Block pointers require copy/dispose.
378 if (variable->getType()->isBlockPointerType()) {
379 info.NeedsCopyDispose = true;
380
381 // So do Objective-C pointers.
382 } else if (variable->getType()->isObjCObjectPointerType() ||
383 C.isObjCNSObjectType(variable->getType())) {
384 info.NeedsCopyDispose = true;
385
386 // So do types that require non-trivial copy construction.
387 } else if (ci->hasCopyExpr()) {
388 info.NeedsCopyDispose = true;
389 info.HasCXXObject = true;
390
391 // And so do types with destructors.
392 } else if (CGM.getLangOptions().CPlusPlus) {
393 if (const CXXRecordDecl *record =
394 variable->getType()->getAsCXXRecordDecl()) {
395 if (!record->hasTrivialDestructor()) {
396 info.HasCXXObject = true;
397 info.NeedsCopyDispose = true;
398 }
399 }
400 }
401
402 CharUnits size = C.getTypeSizeInChars(variable->getType());
403 CharUnits align = C.getDeclAlign(variable);
404 maxFieldAlign = std::max(maxFieldAlign, align);
405
406 const llvm::Type *llvmType =
407 CGM.getTypes().ConvertTypeForMem(variable->getType());
408
409 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
410 }
411
412 // If that was everything, we're done here.
413 if (layout.empty()) {
414 info.StructureType =
415 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
416 info.CanBeGlobal = true;
417 return;
418 }
419
420 // Sort the layout by alignment. We have to use a stable sort here
421 // to get reproducible results. There should probably be an
422 // llvm::array_pod_stable_sort.
423 std::stable_sort(layout.begin(), layout.end());
424
425 CharUnits &blockSize = info.BlockSize;
426 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
427
428 // Assuming that the first byte in the header is maximally aligned,
429 // get the alignment of the first byte following the header.
430 CharUnits endAlign = getLowBit(blockSize);
431
432 // If the end of the header isn't satisfactorily aligned for the
433 // maximum thing, look for things that are okay with the header-end
434 // alignment, and keep appending them until we get something that's
435 // aligned right. This algorithm is only guaranteed optimal if
436 // that condition is satisfied at some point; otherwise we can get
437 // things like:
438 // header // next byte has alignment 4
439 // something_with_size_5; // next byte has alignment 1
440 // something_with_alignment_8;
441 // which has 7 bytes of padding, as opposed to the naive solution
442 // which might have less (?).
443 if (endAlign < maxFieldAlign) {
444 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
445 li = layout.begin() + 1, le = layout.end();
446
447 // Look for something that the header end is already
448 // satisfactorily aligned for.
449 for (; li != le && endAlign < li->Alignment; ++li)
450 ;
451
452 // If we found something that's naturally aligned for the end of
453 // the header, keep adding things...
454 if (li != le) {
455 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
456 for (; li != le; ++li) {
457 assert(endAlign >= li->Alignment);
458
459 li->setIndex(info, elementTypes.size());
460 elementTypes.push_back(li->Type);
461 blockSize += li->Size;
462 endAlign = getLowBit(blockSize);
463
464 // ...until we get to the alignment of the maximum field.
465 if (endAlign >= maxFieldAlign)
466 break;
467 }
468
469 // Don't re-append everything we just appended.
470 layout.erase(first, li);
471 }
472 }
473
474 // At this point, we just have to add padding if the end align still
475 // isn't aligned right.
476 if (endAlign < maxFieldAlign) {
477 CharUnits padding = maxFieldAlign - endAlign;
478
John McCall5936e332011-02-15 09:22:45 +0000479 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
480 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000481 blockSize += padding;
482
483 endAlign = getLowBit(blockSize);
484 assert(endAlign >= maxFieldAlign);
485 }
486
487 // Slam everything else on now. This works because they have
488 // strictly decreasing alignment and we expect that size is always a
489 // multiple of alignment.
490 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
491 li = layout.begin(), le = layout.end(); li != le; ++li) {
492 assert(endAlign >= li->Alignment);
493 li->setIndex(info, elementTypes.size());
494 elementTypes.push_back(li->Type);
495 blockSize += li->Size;
496 endAlign = getLowBit(blockSize);
497 }
498
499 info.StructureType =
500 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
501}
502
503/// Emit a block literal expression in the current function.
504llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
505 std::string Name = CurFn->getName();
506 CGBlockInfo blockInfo(blockExpr, Name.c_str());
507
508 // Compute information about the layout, etc., of this block.
509 computeBlockInfo(CGM, blockInfo);
510
511 // Using that metadata, generate the actual block function.
512 llvm::Constant *blockFn
513 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
514 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000515 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000516
517 // If there is nothing to capture, we can emit this as a global block.
518 if (blockInfo.CanBeGlobal)
519 return buildGlobalBlock(CGM, blockInfo, blockFn);
520
521 // Otherwise, we have to emit this as a local block.
522
523 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000524 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000525
526 // Build the block descriptor.
527 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
528
529 const llvm::Type *intTy = ConvertType(getContext().IntTy);
530
531 llvm::AllocaInst *blockAddr =
532 CreateTempAlloca(blockInfo.StructureType, "block");
533 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
534
535 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000536 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000537 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
538 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
539 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
540
541 // Initialize the block literal.
542 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000543 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000544 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
545 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
546 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
547 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
548 "block.invoke"));
549 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
550 "block.descriptor"));
551
552 // Finally, capture all the values into the block.
553 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
554
555 // First, 'this'.
556 if (blockDecl->capturesCXXThis()) {
557 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
558 blockInfo.CXXThisIndex,
559 "block.captured-this.addr");
560 Builder.CreateStore(LoadCXXThis(), addr);
561 }
562
563 // Next, captured variables.
564 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
565 ce = blockDecl->capture_end(); ci != ce; ++ci) {
566 const VarDecl *variable = ci->getVariable();
567 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
568
569 // Ignore constant captures.
570 if (capture.isConstant()) continue;
571
572 QualType type = variable->getType();
573
574 // This will be a [[type]]*, except that a byref entry will just be
575 // an i8**.
576 llvm::Value *blockField =
577 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
578 "block.captured");
579
580 // Compute the address of the thing we're going to move into the
581 // block literal.
582 llvm::Value *src;
583 if (ci->isNested()) {
584 // We need to use the capture from the enclosing block.
585 const CGBlockInfo::Capture &enclosingCapture =
586 BlockInfo->getCapture(variable);
587
588 // This is a [[type]]*, except that a byref entry wil just be an i8**.
589 src = Builder.CreateStructGEP(LoadBlockStruct(),
590 enclosingCapture.getIndex(),
591 "block.capture.addr");
592 } else {
593 // This is a [[type]]*.
594 src = LocalDeclMap[variable];
595 }
596
597 // For byrefs, we just write the pointer to the byref struct into
598 // the block field. There's no need to chase the forwarding
599 // pointer at this point, since we're building something that will
600 // live a shorter life than the stack byref anyway.
601 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000602 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000603 if (ci->isNested())
604 src = Builder.CreateLoad(src, "byref.capture");
605 else
John McCall5936e332011-02-15 09:22:45 +0000606 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000607
John McCall5936e332011-02-15 09:22:45 +0000608 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000609 Builder.CreateStore(src, blockField);
610
611 // If we have a copy constructor, evaluate that into the block field.
612 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
613 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
614
615 // If it's a reference variable, copy the reference into the block field.
616 } else if (type->isReferenceType()) {
617 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
618
619 // Otherwise, fake up a POD copy into the block field.
620 } else {
John McCallbb699b02011-02-07 18:37:40 +0000621 // We use one of these or the other depending on whether the
622 // reference is nested.
623 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
624 SourceLocation());
625 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
626 VK_LValue, SourceLocation(), /*byref*/ false);
627
628 Expr *declRef =
629 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
630
John McCall6b5a61b2011-02-07 10:33:21 +0000631 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000632 declRef, VK_RValue);
John McCalldf045202011-03-08 09:38:48 +0000633 EmitExprAsInit(&l2r, variable, blockField,
634 getContext().getDeclAlign(variable),
635 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000636 }
637
638 // Push a destructor if necessary. The semantics for when this
639 // actually gets run are really obscure.
640 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
641 PushDestructorCleanup(type, blockField);
642 }
643
644 // Cast to the converted block-pointer type, which happens (somewhat
645 // unfortunately) to be a pointer to function type.
646 llvm::Value *result =
647 Builder.CreateBitCast(blockAddr,
648 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000649
John McCall6b5a61b2011-02-07 10:33:21 +0000650 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000651}
652
653
John McCalld16c2cf2011-02-08 08:22:06 +0000654const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000655 if (BlockDescriptorType)
656 return BlockDescriptorType;
657
Mike Stumpa5448542009-02-13 15:32:32 +0000658 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000659 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000660
Mike Stumpab695142009-02-13 15:16:56 +0000661 // struct __block_descriptor {
662 // unsigned long reserved;
663 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000664 //
665 // // later, the following will be added
666 //
667 // struct {
668 // void (*copyHelper)();
669 // void (*copyHelper)();
670 // } helpers; // !!! optional
671 //
672 // const char *signature; // the block signature
673 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000674 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000675 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
676 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000677 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000678 NULL);
679
680 getModule().addTypeName("struct.__block_descriptor",
681 BlockDescriptorType);
682
John McCall6b5a61b2011-02-07 10:33:21 +0000683 // Now form a pointer to that.
684 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000685 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000686}
687
John McCalld16c2cf2011-02-08 08:22:06 +0000688const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000689 if (GenericBlockLiteralType)
690 return GenericBlockLiteralType;
691
John McCall6b5a61b2011-02-07 10:33:21 +0000692 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000693
Mike Stump9b8a7972009-02-13 15:25:34 +0000694 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000695 // void *__isa;
696 // int __flags;
697 // int __reserved;
698 // void (*__invoke)(void *);
699 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000700 // };
John McCall5936e332011-02-15 09:22:45 +0000701 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
702 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000703 IntTy,
704 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000705 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000706 BlockDescPtrTy,
707 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000708
Mike Stump9b8a7972009-02-13 15:25:34 +0000709 getModule().addTypeName("struct.__block_literal_generic",
710 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000711
Mike Stump9b8a7972009-02-13 15:25:34 +0000712 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000713}
714
Mike Stumpbd65cac2009-02-19 01:01:04 +0000715
Anders Carlssona1736c02009-12-24 21:13:40 +0000716RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
717 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000718 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000719 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000720
Anders Carlssonacfde802009-02-12 00:39:25 +0000721 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
722
723 // Get a pointer to the generic block literal.
724 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000725 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000726
727 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000728 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000729 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
730
731 // Get the function pointer from the literal.
732 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000733
John McCall5936e332011-02-15 09:22:45 +0000734 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000735
Anders Carlssonacfde802009-02-12 00:39:25 +0000736 // Add the block literal.
737 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
738 CallArgList Args;
739 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000740
Anders Carlsson782f3972009-04-08 23:13:16 +0000741 QualType FnType = BPT->getPointeeType();
742
Anders Carlssonacfde802009-02-12 00:39:25 +0000743 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000744 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000745 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000746
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000747 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000748 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000749
John McCall04a67a62010-02-05 21:31:56 +0000750 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
751 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000752
Mike Stump1eb44332009-09-09 15:08:12 +0000753 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000754 CGM.getTypes().getFunctionInfo(ResultType, Args,
755 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000757 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000758 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000759 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Owen Anderson96e0fc72009-07-29 22:16:19 +0000761 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000762 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Anders Carlssonacfde802009-02-12 00:39:25 +0000764 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000765 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000766}
Anders Carlssond5cab542009-02-12 17:55:02 +0000767
John McCall6b5a61b2011-02-07 10:33:21 +0000768llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
769 bool isByRef) {
770 assert(BlockInfo && "evaluating block ref without block information?");
771 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000772
John McCall6b5a61b2011-02-07 10:33:21 +0000773 // Handle constant captures.
774 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000775
John McCall6b5a61b2011-02-07 10:33:21 +0000776 llvm::Value *addr =
777 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
778 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000779
John McCall6b5a61b2011-02-07 10:33:21 +0000780 if (isByRef) {
781 // addr should be a void** right now. Load, then cast the result
782 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000783
John McCall6b5a61b2011-02-07 10:33:21 +0000784 addr = Builder.CreateLoad(addr);
785 const llvm::PointerType *byrefPointerType
786 = llvm::PointerType::get(BuildByRefType(variable), 0);
787 addr = Builder.CreateBitCast(addr, byrefPointerType,
788 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000789
John McCall6b5a61b2011-02-07 10:33:21 +0000790 // Follow the forwarding pointer.
791 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
792 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000793
John McCall6b5a61b2011-02-07 10:33:21 +0000794 // Cast back to byref* and GEP over to the actual object.
795 addr = Builder.CreateBitCast(addr, byrefPointerType);
796 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
797 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000798 }
799
John McCall6b5a61b2011-02-07 10:33:21 +0000800 if (variable->getType()->isReferenceType())
801 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000802
John McCall6b5a61b2011-02-07 10:33:21 +0000803 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000804}
805
Mike Stump67a64482009-02-14 22:16:35 +0000806llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000807CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000808 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000809 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000810
John McCall6b5a61b2011-02-07 10:33:21 +0000811 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000812 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000813
John McCall6b5a61b2011-02-07 10:33:21 +0000814 // Using that metadata, generate the actual block function.
815 llvm::Constant *blockFn;
816 {
817 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000818 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
819 blockInfo,
820 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000821 }
John McCall5936e332011-02-15 09:22:45 +0000822 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000823
John McCalld16c2cf2011-02-08 08:22:06 +0000824 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000825}
826
John McCall6b5a61b2011-02-07 10:33:21 +0000827static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
828 const CGBlockInfo &blockInfo,
829 llvm::Constant *blockFn) {
830 assert(blockInfo.CanBeGlobal);
831
832 // Generate the constants for the block literal initializer.
833 llvm::Constant *fields[BlockHeaderSize];
834
835 // isa
836 fields[0] = CGM.getNSConcreteGlobalBlock();
837
838 // __flags
John McCalld16c2cf2011-02-08 08:22:06 +0000839 BlockFlags flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
840 BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
John McCall5936e332011-02-15 09:22:45 +0000841 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000842
843 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000844 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000845
846 // Function
847 fields[3] = blockFn;
848
849 // Descriptor
850 fields[4] = buildBlockDescriptor(CGM, blockInfo);
851
852 llvm::Constant *init =
853 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
854 /*packed*/ false);
855
856 llvm::GlobalVariable *literal =
857 new llvm::GlobalVariable(CGM.getModule(),
858 init->getType(),
859 /*constant*/ true,
860 llvm::GlobalVariable::InternalLinkage,
861 init,
862 "__block_literal_global");
863 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
864
865 // Return a constant of the appropriately-casted type.
866 const llvm::Type *requiredType =
867 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
868 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000869}
870
Mike Stump00470a12009-03-05 08:32:30 +0000871llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000872CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
873 const CGBlockInfo &blockInfo,
874 const Decl *outerFnDecl,
875 const DeclMapTy &ldm) {
876 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000877
Devang Patel6d1155b2011-03-07 21:53:18 +0000878 // Check if we should generate debug info for this block function.
879 if (CGM.getModuleDebugInfo())
880 DebugInfo = CGM.getModuleDebugInfo();
881
John McCall6b5a61b2011-02-07 10:33:21 +0000882 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Mike Stump7f28a9c2009-03-13 23:34:28 +0000884 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000885 // to be local to this function as well, in case they're directly
886 // referenced in a block.
887 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
888 const VarDecl *var = dyn_cast<VarDecl>(i->first);
889 if (var && !var->hasLocalStorage())
890 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000891 }
892
John McCall6b5a61b2011-02-07 10:33:21 +0000893 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000894
John McCall6b5a61b2011-02-07 10:33:21 +0000895 // Build the argument list.
896 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000897
John McCall6b5a61b2011-02-07 10:33:21 +0000898 // The first argument is the block pointer. Just take it as a void*
899 // and cast it later.
900 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000901 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000902
John McCall8178df32011-02-22 22:38:33 +0000903 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
904 SourceLocation(), II, selfTy);
905 args.push_back(std::make_pair(&selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 // Now add the rest of the parameters.
908 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
909 e = blockDecl->param_end(); i != e; ++i)
910 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Create the function declaration.
913 const FunctionProtoType *fnType =
914 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
915 const CGFunctionInfo &fnInfo =
916 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
917 fnType->getExtInfo());
918 const llvm::FunctionType *fnLLVMType =
919 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000920
John McCall6b5a61b2011-02-07 10:33:21 +0000921 MangleBuffer name;
922 CGM.getBlockMangledName(GD, name, blockDecl);
923 llvm::Function *fn =
924 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
925 name.getString(), &CGM.getModule());
926 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000927
John McCall6b5a61b2011-02-07 10:33:21 +0000928 // Begin generating the function.
929 StartFunction(blockDecl, fnType->getResultType(), fn, args,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000930 blockInfo.getBlockExpr()->getBody()->getLocEnd());
John McCall6b5a61b2011-02-07 10:33:21 +0000931 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000932
John McCall8178df32011-02-22 22:38:33 +0000933 // Okay. Undo some of what StartFunction did.
934
935 // Pull the 'self' reference out of the local decl map.
936 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
937 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000938 BlockPointer = Builder.CreateBitCast(blockAddr,
939 blockInfo.StructureType->getPointerTo(),
940 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000941
John McCallea1471e2010-05-20 01:18:31 +0000942 // If we have a C++ 'this' reference, go ahead and force it into
943 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000944 if (blockDecl->capturesCXXThis()) {
945 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
946 blockInfo.CXXThisIndex,
947 "block.captured-this");
948 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000949 }
950
John McCall6b5a61b2011-02-07 10:33:21 +0000951 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
952 // appease it.
953 if (const ObjCMethodDecl *method
954 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
955 const VarDecl *self = method->getSelfDecl();
956
957 // There might not be a capture for 'self', but if there is...
958 if (blockInfo.Captures.count(self)) {
959 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
960 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
961 capture.getIndex(),
962 "block.captured-self");
963 LocalDeclMap[self] = selfAddr;
964 }
965 }
966
967 // Also force all the constant captures.
968 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
969 ce = blockDecl->capture_end(); ci != ce; ++ci) {
970 const VarDecl *variable = ci->getVariable();
971 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
972 if (!capture.isConstant()) continue;
973
974 unsigned align = getContext().getDeclAlign(variable).getQuantity();
975
976 llvm::AllocaInst *alloca =
977 CreateMemTemp(variable->getType(), "block.captured-const");
978 alloca->setAlignment(align);
979
980 Builder.CreateStore(capture.getConstant(), alloca, align);
981
982 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000983 }
984
Mike Stumpb289b3f2009-10-01 22:29:41 +0000985 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
986 llvm::BasicBlock *entry = Builder.GetInsertBlock();
987 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
988 --entry_ptr;
989
John McCall6b5a61b2011-02-07 10:33:21 +0000990 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000991
Mike Stumpde8c5c72009-10-01 00:27:30 +0000992 // Remember where we were...
993 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000994
Mike Stumpde8c5c72009-10-01 00:27:30 +0000995 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000996 ++entry_ptr;
997 Builder.SetInsertPoint(entry, entry_ptr);
998
John McCall6b5a61b2011-02-07 10:33:21 +0000999 // Emit debug information for all the BlockDeclRefDecls.
1000 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001001 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001002 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1003 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1004 const VarDecl *variable = ci->getVariable();
1005 DI->setLocation(variable->getLocation());
1006
1007 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1008 if (capture.isConstant()) {
1009 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1010 Builder);
1011 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001012 }
John McCall6b5a61b2011-02-07 10:33:21 +00001013
John McCall8178df32011-02-22 22:38:33 +00001014 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001015 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001016 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001017 }
John McCall6b5a61b2011-02-07 10:33:21 +00001018
Mike Stumpde8c5c72009-10-01 00:27:30 +00001019 // And resume where we left off.
1020 if (resume == 0)
1021 Builder.ClearInsertionPoint();
1022 else
1023 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001024
John McCall6b5a61b2011-02-07 10:33:21 +00001025 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001026
John McCall6b5a61b2011-02-07 10:33:21 +00001027 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001028}
Mike Stumpa99038c2009-02-28 09:07:16 +00001029
John McCall6b5a61b2011-02-07 10:33:21 +00001030/*
1031 notes.push_back(HelperInfo());
1032 HelperInfo &note = notes.back();
1033 note.index = capture.getIndex();
1034 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1035 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001036
John McCall6b5a61b2011-02-07 10:33:21 +00001037 if (ci->isByRef()) {
1038 note.flag = BLOCK_FIELD_IS_BYREF;
1039 if (type.isObjCGCWeak())
1040 note.flag |= BLOCK_FIELD_IS_WEAK;
1041 } else if (type->isBlockPointerType()) {
1042 note.flag = BLOCK_FIELD_IS_BLOCK;
1043 } else {
1044 note.flag = BLOCK_FIELD_IS_OBJECT;
1045 }
1046 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001047
Mike Stump00470a12009-03-05 08:32:30 +00001048
Mike Stumpa99038c2009-02-28 09:07:16 +00001049
Mike Stumpdab514f2009-03-04 03:23:46 +00001050
Mike Stumpa4f668f2009-03-06 01:33:24 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001053CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001054 ASTContext &C = getContext();
1055
1056 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001057 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001058 ImplicitParamDecl *dstDecl =
1059 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1060 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1061 ImplicitParamDecl *srcDecl =
1062 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1063 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Mike Stumpa4f668f2009-03-06 01:33:24 +00001065 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001066 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001067
John McCall6b5a61b2011-02-07 10:33:21 +00001068 // FIXME: it would be nice if these were mergeable with things with
1069 // identical semantics.
1070 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001071
1072 llvm::Function *Fn =
1073 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001074 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001075
1076 IdentifierInfo *II
1077 = &CGM.getContext().Idents.get("__copy_helper_block_");
1078
John McCall6b5a61b2011-02-07 10:33:21 +00001079 FunctionDecl *FD = FunctionDecl::Create(C,
1080 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001081 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001082 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001083 SC_Static,
1084 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001085 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001086 true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001087 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001088
John McCall6b5a61b2011-02-07 10:33:21 +00001089 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001090
John McCalld16c2cf2011-02-08 08:22:06 +00001091 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1092 src = Builder.CreateLoad(src);
1093 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001094
John McCalld16c2cf2011-02-08 08:22:06 +00001095 llvm::Value *dst = GetAddrOfLocalVar(dstDecl);
1096 dst = Builder.CreateLoad(dst);
1097 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001098
John McCall6b5a61b2011-02-07 10:33:21 +00001099 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001100
John McCall6b5a61b2011-02-07 10:33:21 +00001101 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1102 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1103 const VarDecl *variable = ci->getVariable();
1104 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001105
John McCall6b5a61b2011-02-07 10:33:21 +00001106 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1107 if (capture.isConstant()) continue;
1108
1109 const Expr *copyExpr = ci->getCopyExpr();
1110 unsigned flags = 0;
1111
1112 if (copyExpr) {
1113 assert(!ci->isByRef());
1114 // don't bother computing flags
1115 } else if (ci->isByRef()) {
1116 flags = BLOCK_FIELD_IS_BYREF;
1117 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1118 } else if (type->isBlockPointerType()) {
1119 flags = BLOCK_FIELD_IS_BLOCK;
1120 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1121 flags = BLOCK_FIELD_IS_OBJECT;
1122 }
1123
1124 if (!copyExpr && !flags) continue;
1125
1126 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001127 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1128 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001129
1130 // If there's an explicit copy expression, we do that.
1131 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001132 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall6b5a61b2011-02-07 10:33:21 +00001133 } else {
1134 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001135 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1136 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001137 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCalld16c2cf2011-02-08 08:22:06 +00001138 llvm::ConstantInt::get(Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001139 }
1140 }
1141
John McCalld16c2cf2011-02-08 08:22:06 +00001142 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001143
John McCall5936e332011-02-15 09:22:45 +00001144 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001145}
1146
John McCall6b5a61b2011-02-07 10:33:21 +00001147llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001148CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001149 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001150
John McCall6b5a61b2011-02-07 10:33:21 +00001151 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001152 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001153 ImplicitParamDecl *srcDecl =
1154 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1155 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Mike Stumpa4f668f2009-03-06 01:33:24 +00001157 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001158 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001159
Mike Stump3899a7f2009-06-05 23:26:36 +00001160 // FIXME: We'd like to put these into a mergable by content, with
1161 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001162 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001163
1164 llvm::Function *Fn =
1165 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001166 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001167
1168 IdentifierInfo *II
1169 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1170
John McCall6b5a61b2011-02-07 10:33:21 +00001171 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001172 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001173 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001174 SC_Static,
1175 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001176 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001177 StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001178
John McCall6b5a61b2011-02-07 10:33:21 +00001179 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001180
John McCalld16c2cf2011-02-08 08:22:06 +00001181 llvm::Value *src = GetAddrOfLocalVar(srcDecl);
1182 src = Builder.CreateLoad(src);
1183 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001184
John McCall6b5a61b2011-02-07 10:33:21 +00001185 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1186
John McCalld16c2cf2011-02-08 08:22:06 +00001187 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001188
1189 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1190 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1191 const VarDecl *variable = ci->getVariable();
1192 QualType type = variable->getType();
1193
1194 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1195 if (capture.isConstant()) continue;
1196
John McCalld16c2cf2011-02-08 08:22:06 +00001197 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001198 const CXXDestructorDecl *dtor = 0;
1199
1200 if (ci->isByRef()) {
1201 flags = BLOCK_FIELD_IS_BYREF;
1202 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1203 } else if (type->isBlockPointerType()) {
1204 flags = BLOCK_FIELD_IS_BLOCK;
1205 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1206 flags = BLOCK_FIELD_IS_OBJECT;
1207 } else if (C.getLangOptions().CPlusPlus) {
1208 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1209 if (!record->hasTrivialDestructor())
1210 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001211 }
John McCall6b5a61b2011-02-07 10:33:21 +00001212
John McCalld16c2cf2011-02-08 08:22:06 +00001213 if (!dtor && flags.empty()) continue;
John McCall6b5a61b2011-02-07 10:33:21 +00001214
1215 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001216 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001217
1218 // If there's an explicit copy expression, we do that.
1219 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001220 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001221
1222 // Otherwise we call _Block_object_dispose. It wouldn't be too
1223 // hard to just emit this as a cleanup if we wanted to make sure
1224 // that things were done in reverse.
1225 } else {
1226 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001227 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001228 BuildBlockRelease(value, flags);
1229 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001230 }
1231
John McCall6b5a61b2011-02-07 10:33:21 +00001232 cleanups.ForceCleanup();
1233
John McCalld16c2cf2011-02-08 08:22:06 +00001234 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001235
John McCall5936e332011-02-15 09:22:45 +00001236 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001237}
1238
John McCalld16c2cf2011-02-08 08:22:06 +00001239llvm::Constant *CodeGenFunction::
1240GeneratebyrefCopyHelperFunction(const llvm::Type *T, BlockFieldFlags flags,
1241 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001242 QualType R = getContext().VoidTy;
1243
1244 FunctionArgList Args;
1245 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001246 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001247 ImplicitParamDecl::Create(getContext(), 0,
1248 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001249 getContext().getPointerType(getContext().VoidTy));
1250 Args.push_back(std::make_pair(Dst, Dst->getType()));
1251
1252 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001253 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001254 ImplicitParamDecl::Create(getContext(), 0,
1255 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001256 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001257 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Mike Stump45031c02009-03-06 02:29:21 +00001259 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001260 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001261
Mike Stump45031c02009-03-06 02:29:21 +00001262 CodeGenTypes &Types = CGM.getTypes();
1263 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1264
Mike Stump3899a7f2009-06-05 23:26:36 +00001265 // FIXME: We'd like to put these into a mergable by content, with
1266 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001267 llvm::Function *Fn =
1268 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001269 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001270
1271 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001272 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001273
1274 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1275 getContext().getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001276 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001277 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001278 SC_Static,
1279 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001280 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001281 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001282
1283 // dst->x
John McCalld16c2cf2011-02-08 08:22:06 +00001284 llvm::Value *V = GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001285 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001286 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001287 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001288 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001289
1290 // src->x
John McCalld16c2cf2011-02-08 08:22:06 +00001291 V = GetAddrOfLocalVar(Src);
Mike Stumpee094222009-03-06 06:12:24 +00001292 V = Builder.CreateLoad(V);
1293 V = Builder.CreateBitCast(V, T);
1294 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001295
John McCalld16c2cf2011-02-08 08:22:06 +00001296 if (Expr *copyExpr = getContext().getBlockVarCopyInits(variable)) {
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001297 llvm::Value *SrcObj = V;
John McCalld16c2cf2011-02-08 08:22:06 +00001298 EmitSynthesizedCXXCopyCtor(DstObj, SrcObj, copyExpr);
1299 } else {
John McCall5936e332011-02-15 09:22:45 +00001300 DstObj = Builder.CreateBitCast(DstObj, VoidPtrTy);
1301 V = Builder.CreateBitCast(V, VoidPtrPtrTy);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001302 llvm::Value *SrcObj = Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +00001303 flags |= BLOCK_BYREF_CALLER;
1304 llvm::Value *N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001305 llvm::Value *F = CGM.getBlockObjectAssign();
1306 Builder.CreateCall3(F, DstObj, SrcObj, N);
1307 }
1308
John McCalld16c2cf2011-02-08 08:22:06 +00001309 FinishFunction();
Mike Stump45031c02009-03-06 02:29:21 +00001310
John McCalld16c2cf2011-02-08 08:22:06 +00001311 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001312}
1313
Mike Stump1851b682009-03-06 04:53:30 +00001314llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001315CodeGenFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1316 BlockFieldFlags flags,
1317 const VarDecl *variable) {
Mike Stump45031c02009-03-06 02:29:21 +00001318 QualType R = getContext().VoidTy;
1319
1320 FunctionArgList Args;
1321 // FIXME: This leaks
1322 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001323 ImplicitParamDecl::Create(getContext(), 0,
1324 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001325 getContext().getPointerType(getContext().VoidTy));
1326
1327 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Mike Stump45031c02009-03-06 02:29:21 +00001329 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001330 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001331
Mike Stump45031c02009-03-06 02:29:21 +00001332 CodeGenTypes &Types = CGM.getTypes();
1333 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1334
Mike Stump3899a7f2009-06-05 23:26:36 +00001335 // FIXME: We'd like to put these into a mergable by content, with
1336 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001337 llvm::Function *Fn =
1338 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001339 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001340 &CGM.getModule());
1341
1342 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001343 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001344
1345 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1346 getContext().getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001347 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001348 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001349 SC_Static,
1350 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001351 false, true);
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001352 StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001353
John McCalld16c2cf2011-02-08 08:22:06 +00001354 llvm::Value *V = GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001355 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001356 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001357 V = Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001358
1359 // If it's not any kind of special object, it must have a destructor
1360 // or something.
1361 if (!flags.isSpecialPointer()) {
1362 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
1363 PushDestructorCleanup(variable->getType(), V);
1364 PopCleanupBlocks(CleanupDepth);
1365
1366 // Otherwise, call _Block_object_dispose.
1367 } else {
1368 V = Builder.CreateBitCast(V, llvm::PointerType::get(Int8PtrTy, 0));
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001369 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001370
John McCalld16c2cf2011-02-08 08:22:06 +00001371 flags |= BLOCK_BYREF_CALLER;
1372 BuildBlockRelease(V, flags);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001373 }
Mike Stump45031c02009-03-06 02:29:21 +00001374
John McCalld16c2cf2011-02-08 08:22:06 +00001375 FinishFunction();
1376
1377 return llvm::ConstantExpr::getBitCast(Fn, Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001378}
1379
John McCalld16c2cf2011-02-08 08:22:06 +00001380llvm::Constant *CodeGenModule::BuildbyrefCopyHelper(const llvm::Type *T,
1381 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001382 unsigned align,
1383 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001384 // All alignments below pointer alignment are bumped up, as we
1385 // always have at least that much alignment to begin with.
1386 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001387
Mike Stump3899a7f2009-06-05 23:26:36 +00001388 // As an optimization, we only generate a single function of each kind we
1389 // might need. We need a different one for each alignment and for each
1390 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001391 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1392 llvm::Constant *&Entry = AssignCache[Kind];
1393 if (!Entry)
1394 Entry = CodeGenFunction(*this).
1395 GeneratebyrefCopyHelperFunction(T, flags, var);
1396 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001397}
1398
John McCalld16c2cf2011-02-08 08:22:06 +00001399llvm::Constant *CodeGenModule::BuildbyrefDestroyHelper(const llvm::Type *T,
1400 BlockFieldFlags flags,
John McCall6b5a61b2011-02-07 10:33:21 +00001401 unsigned align,
1402 const VarDecl *var) {
John McCall34695852011-02-22 06:44:22 +00001403 // All alignments below pointer alignment are bumped up, as we
1404 // always have at least that much alignment to begin with.
1405 if (align < PointerAlignInBytes) align = PointerAlignInBytes;
Chris Lattner10976d92009-12-05 08:21:30 +00001406
Mike Stump3899a7f2009-06-05 23:26:36 +00001407 // As an optimization, we only generate a single function of each kind we
1408 // might need. We need a different one for each alignment and for each
1409 // setting of flags. We mix Align and flag to get the kind.
John McCalld16c2cf2011-02-08 08:22:06 +00001410 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags.getBitMask();
1411 llvm::Constant *&Entry = DestroyCache[Kind];
1412 if (!Entry)
1413 Entry = CodeGenFunction(*this).
1414 GeneratebyrefDestroyHelperFunction(T, flags, var);
1415 return Entry;
Mike Stump45031c02009-03-06 02:29:21 +00001416}
1417
John McCalld16c2cf2011-02-08 08:22:06 +00001418void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001419 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001420 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001421 V = Builder.CreateBitCast(V, Int8PtrTy);
1422 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001423 Builder.CreateCall2(F, V, N);
1424}