blob: bdbc9d3b55515ec83a3ec688fb652b48d467db72 [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"
Mike Stump6cc88f72009-03-20 21:53:12 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000021#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000022#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000023
Anders Carlssonacfde802009-02-12 00:39:25 +000024using namespace clang;
25using namespace CodeGen;
26
John McCall6b5a61b2011-02-07 10:33:21 +000027CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
28 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
29 HasCXXObject(false), HasWeakBlockVariable(false),
30 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
Fariborz Jahanian7edddb82010-07-28 19:07:18 +0000107static unsigned computeBlockFlag(CodeGenModule &CGM,
108 const BlockExpr *BE, unsigned flags) {
109 QualType BPT = BE->getType();
110 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
111 QualType ResultType = ftype->getResultType();
112
113 CallArgList Args;
114 CodeGenTypes &Types = CGM.getTypes();
115 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
116 FunctionType::ExtInfo());
117 if (CGM.ReturnTypeUsesSRet(FnInfo))
118 flags |= CodeGenFunction::BLOCK_USE_STRET;
119 return flags;
120}
121
John McCall6b5a61b2011-02-07 10:33:21 +0000122/*
123 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
126 struct Block_literal {
127 /// Initialized to one of:
128 /// extern void *_NSConcreteStackBlock[];
129 /// extern void *_NSConcreteGlobalBlock[];
130 ///
131 /// In theory, we could start one off malloc'ed by setting
132 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
133 /// this isa:
134 /// extern void *_NSConcreteMallocBlock[];
135 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000136
John McCall6b5a61b2011-02-07 10:33:21 +0000137 /// These are the flags (with corresponding bit number) that the
138 /// compiler is actually supposed to know about.
139 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
140 /// descriptor provides copy and dispose helper functions
141 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
142 /// object with a nontrivial destructor or copy constructor
143 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
144 /// as global memory
145 /// 29. BLOCK_USE_STRET - indicates that the block function
146 /// uses stret, which objc_msgSend needs to know about
147 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
148 /// @encoded signature string
149 /// And we're not supposed to manipulate these:
150 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
151 /// to malloc'ed memory
152 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
153 /// to GC-allocated memory
154 /// Additionally, the bottom 16 bits are a reference count which
155 /// should be zero on the stack.
156 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000157
John McCall6b5a61b2011-02-07 10:33:21 +0000158 /// Reserved; should be zero-initialized.
159 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000160
John McCall6b5a61b2011-02-07 10:33:21 +0000161 /// Function pointer generated from block literal.
162 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000163
John McCall6b5a61b2011-02-07 10:33:21 +0000164 /// Block description metadata generated from block literal.
165 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000166
John McCall6b5a61b2011-02-07 10:33:21 +0000167 /// Captured values follow.
168 _CapturesTypes captures...;
169 };
170 */
David Chisnall5e530af2009-11-17 19:33:30 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172/// The number of fields in a block header.
173const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175namespace {
176 /// A chunk of data that we actually have to capture in the block.
177 struct BlockLayoutChunk {
178 CharUnits Alignment;
179 CharUnits Size;
180 const BlockDecl::Capture *Capture; // null for 'this'
181 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000182
John McCall6b5a61b2011-02-07 10:33:21 +0000183 BlockLayoutChunk(CharUnits align, CharUnits size,
184 const BlockDecl::Capture *capture,
185 const llvm::Type *type)
186 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000187
John McCall6b5a61b2011-02-07 10:33:21 +0000188 /// Tell the block info that this chunk has the given field index.
189 void setIndex(CGBlockInfo &info, unsigned index) {
190 if (!Capture)
191 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000192 else
John McCall6b5a61b2011-02-07 10:33:21 +0000193 info.Captures[Capture->getVariable()]
194 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000195 }
John McCall6b5a61b2011-02-07 10:33:21 +0000196 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000197
John McCall6b5a61b2011-02-07 10:33:21 +0000198 /// Order by descending alignment.
199 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
200 return left.Alignment > right.Alignment;
201 }
202}
203
204/// It is illegal to modify a const object after initialization.
205/// Therefore, if a const object has a constant initializer, we don't
206/// actually need to keep storage for it in the block; we'll just
207/// rematerialize it at the start of the block function. This is
208/// acceptable because we make no promises about address stability of
209/// captured variables.
210static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
211 const VarDecl *var) {
212 QualType type = var->getType();
213
214 // We can only do this if the variable is const.
215 if (!type.isConstQualified()) return 0;
216
217 // Furthermore, in C++ we can't do this for classes. TODO: we might
218 // actually be able to get away with it for classes with a trivial
219 // destructor and a trivial copy constructor and no mutable fields.
220 if (CGM.getLangOptions().CPlusPlus &&
221 type->getBaseElementTypeUnsafe()->isRecordType())
222 return 0;
223
224 // If the variable doesn't have any initializer (shouldn't this be
225 // invalid?), it's not clear what we should do. Maybe capture as
226 // zero?
227 const Expr *init = var->getInit();
228 if (!init) return 0;
229
230 return CGM.EmitConstantExpr(init, var->getType());
231}
232
233/// Get the low bit of a nonzero character count. This is the
234/// alignment of the nth byte if the 0th byte is universally aligned.
235static CharUnits getLowBit(CharUnits v) {
236 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
237}
238
239static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
240 std::vector<const llvm::Type*> &elementTypes) {
241 ASTContext &C = CGM.getContext();
242
243 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
244 CharUnits ptrSize, ptrAlign, intSize, intAlign;
245 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
246 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
247
248 // Are there crazy embedded platforms where this isn't true?
249 assert(intSize <= ptrSize && "layout assumptions horribly violated");
250
251 CharUnits headerSize = ptrSize;
252 if (2 * intSize < ptrAlign) headerSize += ptrSize;
253 else headerSize += 2 * intSize;
254 headerSize += 2 * ptrSize;
255
256 info.BlockAlign = ptrAlign;
257 info.BlockSize = headerSize;
258
259 assert(elementTypes.empty());
260 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
261 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
262 elementTypes.push_back(i8p);
263 elementTypes.push_back(intTy);
264 elementTypes.push_back(intTy);
265 elementTypes.push_back(i8p);
266 elementTypes.push_back(CGM.getBlockDescriptorType());
267
268 assert(elementTypes.size() == BlockHeaderSize);
269}
270
271/// Compute the layout of the given block. Attempts to lay the block
272/// out with minimal space requirements.
273static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
274 ASTContext &C = CGM.getContext();
275 const BlockDecl *block = info.getBlockDecl();
276
277 std::vector<const llvm::Type*> elementTypes;
278 initializeForBlockHeader(CGM, info, elementTypes);
279
280 if (!block->hasCaptures()) {
281 info.StructureType =
282 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
283 info.CanBeGlobal = true;
284 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000285 }
Mike Stump00470a12009-03-05 08:32:30 +0000286
John McCall6b5a61b2011-02-07 10:33:21 +0000287 // Collect the layout chunks.
288 llvm::SmallVector<BlockLayoutChunk, 16> layout;
289 layout.reserve(block->capturesCXXThis() +
290 (block->capture_end() - block->capture_begin()));
291
292 CharUnits maxFieldAlign;
293
294 // First, 'this'.
295 if (block->capturesCXXThis()) {
296 const DeclContext *DC = block->getDeclContext();
297 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
298 ;
299 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
300
301 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
302 std::pair<CharUnits,CharUnits> tinfo
303 = CGM.getContext().getTypeInfoInChars(thisType);
304 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
305
306 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
307 }
308
309 // Next, all the block captures.
310 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
311 ce = block->capture_end(); ci != ce; ++ci) {
312 const VarDecl *variable = ci->getVariable();
313
314 if (ci->isByRef()) {
315 // We have to copy/dispose of the __block reference.
316 info.NeedsCopyDispose = true;
317
318 // Also note that it's weak for GC purposes.
319 if (variable->getType().isObjCGCWeak())
320 info.HasWeakBlockVariable = true;
321
322 // Just use void* instead of a pointer to the byref type.
323 QualType byRefPtrTy = C.VoidPtrTy;
324
325 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
326 std::pair<CharUnits,CharUnits> tinfo
327 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
328 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
329
330 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
331 &*ci, llvmType));
332 continue;
333 }
334
335 // Otherwise, build a layout chunk with the size and alignment of
336 // the declaration.
337 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
338 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
339 continue;
340 }
341
342 // Block pointers require copy/dispose.
343 if (variable->getType()->isBlockPointerType()) {
344 info.NeedsCopyDispose = true;
345
346 // So do Objective-C pointers.
347 } else if (variable->getType()->isObjCObjectPointerType() ||
348 C.isObjCNSObjectType(variable->getType())) {
349 info.NeedsCopyDispose = true;
350
351 // So do types that require non-trivial copy construction.
352 } else if (ci->hasCopyExpr()) {
353 info.NeedsCopyDispose = true;
354 info.HasCXXObject = true;
355
356 // And so do types with destructors.
357 } else if (CGM.getLangOptions().CPlusPlus) {
358 if (const CXXRecordDecl *record =
359 variable->getType()->getAsCXXRecordDecl()) {
360 if (!record->hasTrivialDestructor()) {
361 info.HasCXXObject = true;
362 info.NeedsCopyDispose = true;
363 }
364 }
365 }
366
367 CharUnits size = C.getTypeSizeInChars(variable->getType());
368 CharUnits align = C.getDeclAlign(variable);
369 maxFieldAlign = std::max(maxFieldAlign, align);
370
371 const llvm::Type *llvmType =
372 CGM.getTypes().ConvertTypeForMem(variable->getType());
373
374 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
375 }
376
377 // If that was everything, we're done here.
378 if (layout.empty()) {
379 info.StructureType =
380 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
381 info.CanBeGlobal = true;
382 return;
383 }
384
385 // Sort the layout by alignment. We have to use a stable sort here
386 // to get reproducible results. There should probably be an
387 // llvm::array_pod_stable_sort.
388 std::stable_sort(layout.begin(), layout.end());
389
390 CharUnits &blockSize = info.BlockSize;
391 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
392
393 // Assuming that the first byte in the header is maximally aligned,
394 // get the alignment of the first byte following the header.
395 CharUnits endAlign = getLowBit(blockSize);
396
397 // If the end of the header isn't satisfactorily aligned for the
398 // maximum thing, look for things that are okay with the header-end
399 // alignment, and keep appending them until we get something that's
400 // aligned right. This algorithm is only guaranteed optimal if
401 // that condition is satisfied at some point; otherwise we can get
402 // things like:
403 // header // next byte has alignment 4
404 // something_with_size_5; // next byte has alignment 1
405 // something_with_alignment_8;
406 // which has 7 bytes of padding, as opposed to the naive solution
407 // which might have less (?).
408 if (endAlign < maxFieldAlign) {
409 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
410 li = layout.begin() + 1, le = layout.end();
411
412 // Look for something that the header end is already
413 // satisfactorily aligned for.
414 for (; li != le && endAlign < li->Alignment; ++li)
415 ;
416
417 // If we found something that's naturally aligned for the end of
418 // the header, keep adding things...
419 if (li != le) {
420 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
421 for (; li != le; ++li) {
422 assert(endAlign >= li->Alignment);
423
424 li->setIndex(info, elementTypes.size());
425 elementTypes.push_back(li->Type);
426 blockSize += li->Size;
427 endAlign = getLowBit(blockSize);
428
429 // ...until we get to the alignment of the maximum field.
430 if (endAlign >= maxFieldAlign)
431 break;
432 }
433
434 // Don't re-append everything we just appended.
435 layout.erase(first, li);
436 }
437 }
438
439 // At this point, we just have to add padding if the end align still
440 // isn't aligned right.
441 if (endAlign < maxFieldAlign) {
442 CharUnits padding = maxFieldAlign - endAlign;
443
444 const llvm::Type *i8 = llvm::IntegerType::get(CGM.getLLVMContext(), 8);
445 elementTypes.push_back(llvm::ArrayType::get(i8, padding.getQuantity()));
446 blockSize += padding;
447
448 endAlign = getLowBit(blockSize);
449 assert(endAlign >= maxFieldAlign);
450 }
451
452 // Slam everything else on now. This works because they have
453 // strictly decreasing alignment and we expect that size is always a
454 // multiple of alignment.
455 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
456 li = layout.begin(), le = layout.end(); li != le; ++li) {
457 assert(endAlign >= li->Alignment);
458 li->setIndex(info, elementTypes.size());
459 elementTypes.push_back(li->Type);
460 blockSize += li->Size;
461 endAlign = getLowBit(blockSize);
462 }
463
464 info.StructureType =
465 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
466}
467
468/// Emit a block literal expression in the current function.
469llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
470 std::string Name = CurFn->getName();
471 CGBlockInfo blockInfo(blockExpr, Name.c_str());
472
473 // Compute information about the layout, etc., of this block.
474 computeBlockInfo(CGM, blockInfo);
475
476 // Using that metadata, generate the actual block function.
477 llvm::Constant *blockFn
478 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
479 CurFuncDecl, LocalDeclMap);
480 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
481
482 // If there is nothing to capture, we can emit this as a global block.
483 if (blockInfo.CanBeGlobal)
484 return buildGlobalBlock(CGM, blockInfo, blockFn);
485
486 // Otherwise, we have to emit this as a local block.
487
488 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
489 isa = llvm::ConstantExpr::getBitCast(isa, PtrToInt8Ty);
490
491 // Build the block descriptor.
492 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
493
494 const llvm::Type *intTy = ConvertType(getContext().IntTy);
495
496 llvm::AllocaInst *blockAddr =
497 CreateTempAlloca(blockInfo.StructureType, "block");
498 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
499
500 // Compute the initial on-stack block flags.
501 unsigned int flags = BLOCK_HAS_SIGNATURE;
502 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
503 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
504 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
505
506 // Initialize the block literal.
507 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
508 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags),
509 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
510 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
511 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
512 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
513 "block.invoke"));
514 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
515 "block.descriptor"));
516
517 // Finally, capture all the values into the block.
518 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
519
520 // First, 'this'.
521 if (blockDecl->capturesCXXThis()) {
522 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
523 blockInfo.CXXThisIndex,
524 "block.captured-this.addr");
525 Builder.CreateStore(LoadCXXThis(), addr);
526 }
527
528 // Next, captured variables.
529 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
530 ce = blockDecl->capture_end(); ci != ce; ++ci) {
531 const VarDecl *variable = ci->getVariable();
532 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
533
534 // Ignore constant captures.
535 if (capture.isConstant()) continue;
536
537 QualType type = variable->getType();
538
539 // This will be a [[type]]*, except that a byref entry will just be
540 // an i8**.
541 llvm::Value *blockField =
542 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
543 "block.captured");
544
545 // Compute the address of the thing we're going to move into the
546 // block literal.
547 llvm::Value *src;
548 if (ci->isNested()) {
549 // We need to use the capture from the enclosing block.
550 const CGBlockInfo::Capture &enclosingCapture =
551 BlockInfo->getCapture(variable);
552
553 // This is a [[type]]*, except that a byref entry wil just be an i8**.
554 src = Builder.CreateStructGEP(LoadBlockStruct(),
555 enclosingCapture.getIndex(),
556 "block.capture.addr");
557 } else {
558 // This is a [[type]]*.
559 src = LocalDeclMap[variable];
560 }
561
562 // For byrefs, we just write the pointer to the byref struct into
563 // the block field. There's no need to chase the forwarding
564 // pointer at this point, since we're building something that will
565 // live a shorter life than the stack byref anyway.
566 if (ci->isByRef()) {
567 // Get an i8* that points to the byref struct.
568 if (ci->isNested())
569 src = Builder.CreateLoad(src, "byref.capture");
570 else
571 src = Builder.CreateBitCast(src, PtrToInt8Ty);
572
573 // Write that i8* into the capture field.
574 Builder.CreateStore(src, blockField);
575
576 // If we have a copy constructor, evaluate that into the block field.
577 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
578 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
579
580 // If it's a reference variable, copy the reference into the block field.
581 } else if (type->isReferenceType()) {
582 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
583
584 // Otherwise, fake up a POD copy into the block field.
585 } else {
586 DeclRefExpr declRef(const_cast<VarDecl*>(variable), type, VK_LValue,
587 SourceLocation());
588 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
589 &declRef, VK_RValue);
590 EmitAnyExprToMem(&l2r, blockField, /*volatile*/ false, /*init*/ true);
591 }
592
593 // Push a destructor if necessary. The semantics for when this
594 // actually gets run are really obscure.
595 if (!ci->isByRef() && CGM.getLangOptions().CPlusPlus)
596 PushDestructorCleanup(type, blockField);
597 }
598
599 // Cast to the converted block-pointer type, which happens (somewhat
600 // unfortunately) to be a pointer to function type.
601 llvm::Value *result =
602 Builder.CreateBitCast(blockAddr,
603 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000604
605 // We must call objc_read_weak on the block literal itself if it closes
606 // on any __weak __block variables. For some reason.
John McCall6b5a61b2011-02-07 10:33:21 +0000607 if (blockInfo.HasWeakBlockVariable) {
608 const llvm::Type *OrigTy = result->getType();
John McCall711c52b2011-01-05 12:14:39 +0000609
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000610 // Must cast argument to id*
611 const llvm::Type *ObjectPtrTy =
612 ConvertType(CGM.getContext().getObjCIdType());
613 const llvm::Type *PtrObjectPtrTy =
614 llvm::PointerType::getUnqual(ObjectPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000615 result = Builder.CreateBitCast(result, PtrObjectPtrTy);
616 result = CGM.getObjCRuntime().EmitObjCWeakRead(*this, result);
John McCall711c52b2011-01-05 12:14:39 +0000617
618 // Cast back to the original type.
John McCall6b5a61b2011-02-07 10:33:21 +0000619 result = Builder.CreateBitCast(result, OrigTy);
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000620 }
John McCall6b5a61b2011-02-07 10:33:21 +0000621 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000622}
623
624
Mike Stump2a998142009-03-04 18:17:45 +0000625const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000626 if (BlockDescriptorType)
627 return BlockDescriptorType;
628
Mike Stumpa5448542009-02-13 15:32:32 +0000629 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000630 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000631
Mike Stumpab695142009-02-13 15:16:56 +0000632 // struct __block_descriptor {
633 // unsigned long reserved;
634 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000635 //
636 // // later, the following will be added
637 //
638 // struct {
639 // void (*copyHelper)();
640 // void (*copyHelper)();
641 // } helpers; // !!! optional
642 //
643 // const char *signature; // the block signature
644 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000645 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000646 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
647 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000648 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000649 NULL);
650
651 getModule().addTypeName("struct.__block_descriptor",
652 BlockDescriptorType);
653
John McCall6b5a61b2011-02-07 10:33:21 +0000654 // Now form a pointer to that.
655 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000656 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000657}
658
Mike Stump2a998142009-03-04 18:17:45 +0000659const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000660 if (GenericBlockLiteralType)
661 return GenericBlockLiteralType;
662
John McCall6b5a61b2011-02-07 10:33:21 +0000663 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000664
Mike Stump7cbb3602009-02-13 16:01:35 +0000665 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
666 getTypes().ConvertType(getContext().IntTy));
667
Mike Stump9b8a7972009-02-13 15:25:34 +0000668 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000669 // void *__isa;
670 // int __flags;
671 // int __reserved;
672 // void (*__invoke)(void *);
673 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000674 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000675 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000676 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000677 IntTy,
678 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000679 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000680 BlockDescPtrTy,
681 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000682
Mike Stump9b8a7972009-02-13 15:25:34 +0000683 getModule().addTypeName("struct.__block_literal_generic",
684 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000685
Mike Stump9b8a7972009-02-13 15:25:34 +0000686 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000687}
688
Mike Stumpbd65cac2009-02-19 01:01:04 +0000689
Anders Carlssona1736c02009-12-24 21:13:40 +0000690RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
691 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000692 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000693 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000694
Anders Carlssonacfde802009-02-12 00:39:25 +0000695 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
696
697 // Get a pointer to the generic block literal.
698 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000699 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000700
701 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000702 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000703 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
704
705 // Get the function pointer from the literal.
706 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000707
Mike Stumpa5448542009-02-13 15:32:32 +0000708 BlockLiteral =
709 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000710 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000711 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000712
Anders Carlssonacfde802009-02-12 00:39:25 +0000713 // Add the block literal.
714 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
715 CallArgList Args;
716 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000717
Anders Carlsson782f3972009-04-08 23:13:16 +0000718 QualType FnType = BPT->getPointeeType();
719
Anders Carlssonacfde802009-02-12 00:39:25 +0000720 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000721 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000722 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000723
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000724 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000725 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000726
John McCall04a67a62010-02-05 21:31:56 +0000727 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
728 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000729
Mike Stump1eb44332009-09-09 15:08:12 +0000730 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000731 CGM.getTypes().getFunctionInfo(ResultType, Args,
732 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000734 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000735 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000736 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Owen Anderson96e0fc72009-07-29 22:16:19 +0000738 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000739 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Anders Carlssonacfde802009-02-12 00:39:25 +0000741 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000742 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000743}
Anders Carlssond5cab542009-02-12 17:55:02 +0000744
John McCall6b5a61b2011-02-07 10:33:21 +0000745llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
746 bool isByRef) {
747 assert(BlockInfo && "evaluating block ref without block information?");
748 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000749
John McCall6b5a61b2011-02-07 10:33:21 +0000750 // Handle constant captures.
751 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000752
John McCall6b5a61b2011-02-07 10:33:21 +0000753 llvm::Value *addr =
754 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
755 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000756
John McCall6b5a61b2011-02-07 10:33:21 +0000757 if (isByRef) {
758 // addr should be a void** right now. Load, then cast the result
759 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000760
John McCall6b5a61b2011-02-07 10:33:21 +0000761 addr = Builder.CreateLoad(addr);
762 const llvm::PointerType *byrefPointerType
763 = llvm::PointerType::get(BuildByRefType(variable), 0);
764 addr = Builder.CreateBitCast(addr, byrefPointerType,
765 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000766
John McCall6b5a61b2011-02-07 10:33:21 +0000767 // Follow the forwarding pointer.
768 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
769 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000770
John McCall6b5a61b2011-02-07 10:33:21 +0000771 // Cast back to byref* and GEP over to the actual object.
772 addr = Builder.CreateBitCast(addr, byrefPointerType);
773 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
774 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000775 }
776
John McCall6b5a61b2011-02-07 10:33:21 +0000777 if (variable->getType()->isReferenceType())
778 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000779
John McCall6b5a61b2011-02-07 10:33:21 +0000780 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000781}
782
Mike Stump67a64482009-02-14 22:16:35 +0000783llvm::Constant *
John McCall6b5a61b2011-02-07 10:33:21 +0000784BlockModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
785 const char *name) {
786 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000787
John McCall6b5a61b2011-02-07 10:33:21 +0000788 // Compute information about the layout, etc., of this block.
789 computeBlockInfo(CGM, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000790
John McCall6b5a61b2011-02-07 10:33:21 +0000791 // Using that metadata, generate the actual block function.
792 llvm::Constant *blockFn;
793 {
794 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
795 blockFn = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(),
796 blockInfo,
797 0, LocalDeclMap);
798 }
799 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
Mike Stumpa5448542009-02-13 15:32:32 +0000800
John McCall6b5a61b2011-02-07 10:33:21 +0000801 return buildGlobalBlock(CGM, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000802}
803
John McCall6b5a61b2011-02-07 10:33:21 +0000804static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
805 const CGBlockInfo &blockInfo,
806 llvm::Constant *blockFn) {
807 assert(blockInfo.CanBeGlobal);
808
809 // Generate the constants for the block literal initializer.
810 llvm::Constant *fields[BlockHeaderSize];
811
812 // isa
813 fields[0] = CGM.getNSConcreteGlobalBlock();
814
815 // __flags
816 unsigned flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
817 BlockBase::BLOCK_IS_GLOBAL |
818 BlockBase::BLOCK_HAS_SIGNATURE);
819 const llvm::Type *intTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
820 fields[1] = llvm::ConstantInt::get(intTy, flags);
821
822 // Reserved
823 fields[2] = llvm::Constant::getNullValue(intTy);
824
825 // Function
826 fields[3] = blockFn;
827
828 // Descriptor
829 fields[4] = buildBlockDescriptor(CGM, blockInfo);
830
831 llvm::Constant *init =
832 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
833 /*packed*/ false);
834
835 llvm::GlobalVariable *literal =
836 new llvm::GlobalVariable(CGM.getModule(),
837 init->getType(),
838 /*constant*/ true,
839 llvm::GlobalVariable::InternalLinkage,
840 init,
841 "__block_literal_global");
842 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
843
844 // Return a constant of the appropriately-casted type.
845 const llvm::Type *requiredType =
846 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
847 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000848}
849
Mike Stump00470a12009-03-05 08:32:30 +0000850llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000851CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
852 const CGBlockInfo &blockInfo,
853 const Decl *outerFnDecl,
854 const DeclMapTy &ldm) {
855 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000856
John McCall6b5a61b2011-02-07 10:33:21 +0000857 DebugInfo = CGM.getDebugInfo();
858 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Mike Stump7f28a9c2009-03-13 23:34:28 +0000860 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000861 // to be local to this function as well, in case they're directly
862 // referenced in a block.
863 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
864 const VarDecl *var = dyn_cast<VarDecl>(i->first);
865 if (var && !var->hasLocalStorage())
866 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000867 }
868
John McCall6b5a61b2011-02-07 10:33:21 +0000869 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000870
John McCall6b5a61b2011-02-07 10:33:21 +0000871 // Build the argument list.
872 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000873
John McCall6b5a61b2011-02-07 10:33:21 +0000874 // The first argument is the block pointer. Just take it as a void*
875 // and cast it later.
876 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000877 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000878
John McCall6b5a61b2011-02-07 10:33:21 +0000879 // FIXME: this leaks, and we only need it very temporarily.
880 ImplicitParamDecl *selfDecl =
881 ImplicitParamDecl::Create(getContext(),
882 const_cast<BlockDecl*>(blockDecl),
883 SourceLocation(), II, selfTy);
884 args.push_back(std::make_pair(selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000885
John McCall6b5a61b2011-02-07 10:33:21 +0000886 // Now add the rest of the parameters.
887 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
888 e = blockDecl->param_end(); i != e; ++i)
889 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000890
John McCall6b5a61b2011-02-07 10:33:21 +0000891 // Create the function declaration.
892 const FunctionProtoType *fnType =
893 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
894 const CGFunctionInfo &fnInfo =
895 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
896 fnType->getExtInfo());
897 const llvm::FunctionType *fnLLVMType =
898 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000899
John McCall6b5a61b2011-02-07 10:33:21 +0000900 MangleBuffer name;
901 CGM.getBlockMangledName(GD, name, blockDecl);
902 llvm::Function *fn =
903 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
904 name.getString(), &CGM.getModule());
905 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 // Begin generating the function.
908 StartFunction(blockDecl, fnType->getResultType(), fn, args,
909 blockInfo.getBlockExpr()->getBody()->getLocEnd());
910 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Okay. Undo some of what StartFunction did. We really don't need
913 // an alloca for the block address; in theory we could remove it,
914 // but that might do unpleasant things to debug info.
915 llvm::AllocaInst *blockAddrAlloca
916 = cast<llvm::AllocaInst>(LocalDeclMap[selfDecl]);
917 llvm::Value *blockAddr = Builder.CreateLoad(blockAddrAlloca);
918 BlockPointer = Builder.CreateBitCast(blockAddr,
919 blockInfo.StructureType->getPointerTo(),
920 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000921
John McCallea1471e2010-05-20 01:18:31 +0000922 // If we have a C++ 'this' reference, go ahead and force it into
923 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000924 if (blockDecl->capturesCXXThis()) {
925 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
926 blockInfo.CXXThisIndex,
927 "block.captured-this");
928 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000929 }
930
John McCall6b5a61b2011-02-07 10:33:21 +0000931 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
932 // appease it.
933 if (const ObjCMethodDecl *method
934 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
935 const VarDecl *self = method->getSelfDecl();
936
937 // There might not be a capture for 'self', but if there is...
938 if (blockInfo.Captures.count(self)) {
939 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
940 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
941 capture.getIndex(),
942 "block.captured-self");
943 LocalDeclMap[self] = selfAddr;
944 }
945 }
946
947 // Also force all the constant captures.
948 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
949 ce = blockDecl->capture_end(); ci != ce; ++ci) {
950 const VarDecl *variable = ci->getVariable();
951 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
952 if (!capture.isConstant()) continue;
953
954 unsigned align = getContext().getDeclAlign(variable).getQuantity();
955
956 llvm::AllocaInst *alloca =
957 CreateMemTemp(variable->getType(), "block.captured-const");
958 alloca->setAlignment(align);
959
960 Builder.CreateStore(capture.getConstant(), alloca, align);
961
962 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000963 }
964
Mike Stumpb289b3f2009-10-01 22:29:41 +0000965 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
966 llvm::BasicBlock *entry = Builder.GetInsertBlock();
967 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
968 --entry_ptr;
969
John McCall6b5a61b2011-02-07 10:33:21 +0000970 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000971
Mike Stumpde8c5c72009-10-01 00:27:30 +0000972 // Remember where we were...
973 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000974
Mike Stumpde8c5c72009-10-01 00:27:30 +0000975 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000976 ++entry_ptr;
977 Builder.SetInsertPoint(entry, entry_ptr);
978
John McCall6b5a61b2011-02-07 10:33:21 +0000979 // Emit debug information for all the BlockDeclRefDecls.
980 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000981 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000982 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
983 ce = blockDecl->capture_end(); ci != ce; ++ci) {
984 const VarDecl *variable = ci->getVariable();
985 DI->setLocation(variable->getLocation());
986
987 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
988 if (capture.isConstant()) {
989 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
990 Builder);
991 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +0000992 }
John McCall6b5a61b2011-02-07 10:33:21 +0000993
994 DI->EmitDeclareOfBlockDeclRefVariable(variable, blockAddrAlloca,
995 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000996 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000997 }
John McCall6b5a61b2011-02-07 10:33:21 +0000998
Mike Stumpde8c5c72009-10-01 00:27:30 +0000999 // And resume where we left off.
1000 if (resume == 0)
1001 Builder.ClearInsertionPoint();
1002 else
1003 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001004
John McCall6b5a61b2011-02-07 10:33:21 +00001005 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001006
John McCall6b5a61b2011-02-07 10:33:21 +00001007 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001008}
Mike Stumpa99038c2009-02-28 09:07:16 +00001009
John McCall6b5a61b2011-02-07 10:33:21 +00001010/*
1011 notes.push_back(HelperInfo());
1012 HelperInfo &note = notes.back();
1013 note.index = capture.getIndex();
1014 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1015 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001016
John McCall6b5a61b2011-02-07 10:33:21 +00001017 if (ci->isByRef()) {
1018 note.flag = BLOCK_FIELD_IS_BYREF;
1019 if (type.isObjCGCWeak())
1020 note.flag |= BLOCK_FIELD_IS_WEAK;
1021 } else if (type->isBlockPointerType()) {
1022 note.flag = BLOCK_FIELD_IS_BLOCK;
1023 } else {
1024 note.flag = BLOCK_FIELD_IS_OBJECT;
1025 }
1026 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001027
Mike Stump00470a12009-03-05 08:32:30 +00001028
Mike Stumpa99038c2009-02-28 09:07:16 +00001029
Mike Stumpdab514f2009-03-04 03:23:46 +00001030
Mike Stumpa4f668f2009-03-06 01:33:24 +00001031
John McCall6b5a61b2011-02-07 10:33:21 +00001032llvm::Constant *
1033BlockFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1034 ASTContext &C = getContext();
1035
1036 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001037 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001038 ImplicitParamDecl *dstDecl =
1039 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1040 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1041 ImplicitParamDecl *srcDecl =
1042 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1043 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Mike Stumpa4f668f2009-03-06 01:33:24 +00001045 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001046 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001047
John McCall6b5a61b2011-02-07 10:33:21 +00001048 // FIXME: it would be nice if these were mergeable with things with
1049 // identical semantics.
1050 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001051
1052 llvm::Function *Fn =
1053 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001054 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001055
1056 IdentifierInfo *II
1057 = &CGM.getContext().Idents.get("__copy_helper_block_");
1058
John McCall6b5a61b2011-02-07 10:33:21 +00001059 FunctionDecl *FD = FunctionDecl::Create(C,
1060 C.getTranslationUnitDecl(),
1061 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001062 SC_Static,
1063 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001064 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001065 true);
John McCall6b5a61b2011-02-07 10:33:21 +00001066 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001067
John McCall6b5a61b2011-02-07 10:33:21 +00001068 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001069
John McCall6b5a61b2011-02-07 10:33:21 +00001070 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1071 src = CGF.Builder.CreateLoad(src);
1072 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001073
John McCall6b5a61b2011-02-07 10:33:21 +00001074 llvm::Value *dst = CGF.GetAddrOfLocalVar(dstDecl);
1075 dst = CGF.Builder.CreateLoad(dst);
1076 dst = CGF.Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001077
John McCall6b5a61b2011-02-07 10:33:21 +00001078 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001079
John McCall6b5a61b2011-02-07 10:33:21 +00001080 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1081 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1082 const VarDecl *variable = ci->getVariable();
1083 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001084
John McCall6b5a61b2011-02-07 10:33:21 +00001085 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1086 if (capture.isConstant()) continue;
1087
1088 const Expr *copyExpr = ci->getCopyExpr();
1089 unsigned flags = 0;
1090
1091 if (copyExpr) {
1092 assert(!ci->isByRef());
1093 // don't bother computing flags
1094 } else if (ci->isByRef()) {
1095 flags = BLOCK_FIELD_IS_BYREF;
1096 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1097 } else if (type->isBlockPointerType()) {
1098 flags = BLOCK_FIELD_IS_BLOCK;
1099 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1100 flags = BLOCK_FIELD_IS_OBJECT;
1101 }
1102
1103 if (!copyExpr && !flags) continue;
1104
1105 unsigned index = capture.getIndex();
1106 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1107 llvm::Value *dstField = CGF.Builder.CreateStructGEP(dst, index);
1108
1109 // If there's an explicit copy expression, we do that.
1110 if (copyExpr) {
1111 CGF.EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1112 } else {
1113 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1114 srcValue = Builder.CreateBitCast(srcValue, PtrToInt8Ty);
1115 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, PtrToInt8Ty);
1116 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1117 llvm::ConstantInt::get(CGF.Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001118 }
1119 }
1120
Mike Stumpa4f668f2009-03-06 01:33:24 +00001121 CGF.FinishFunction();
1122
Owen Anderson3c4972d2009-07-29 18:54:39 +00001123 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +00001124}
1125
John McCall6b5a61b2011-02-07 10:33:21 +00001126llvm::Constant *
1127BlockFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1128 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001129
John McCall6b5a61b2011-02-07 10:33:21 +00001130 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001131 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001132 ImplicitParamDecl *srcDecl =
1133 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1134 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Mike Stumpa4f668f2009-03-06 01:33:24 +00001136 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001137 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001138
Mike Stump3899a7f2009-06-05 23:26:36 +00001139 // FIXME: We'd like to put these into a mergable by content, with
1140 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001141 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001142
1143 llvm::Function *Fn =
1144 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001145 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001146
1147 IdentifierInfo *II
1148 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1149
John McCall6b5a61b2011-02-07 10:33:21 +00001150 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1151 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001152 SC_Static,
1153 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001154 false, true);
John McCall6b5a61b2011-02-07 10:33:21 +00001155 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001156
John McCall6b5a61b2011-02-07 10:33:21 +00001157 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001158
John McCall6b5a61b2011-02-07 10:33:21 +00001159 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1160 src = CGF.Builder.CreateLoad(src);
1161 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001162
John McCall6b5a61b2011-02-07 10:33:21 +00001163 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1164
1165 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1166
1167 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1168 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1169 const VarDecl *variable = ci->getVariable();
1170 QualType type = variable->getType();
1171
1172 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1173 if (capture.isConstant()) continue;
1174
1175 unsigned flags = 0;
1176 const CXXDestructorDecl *dtor = 0;
1177
1178 if (ci->isByRef()) {
1179 flags = BLOCK_FIELD_IS_BYREF;
1180 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1181 } else if (type->isBlockPointerType()) {
1182 flags = BLOCK_FIELD_IS_BLOCK;
1183 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1184 flags = BLOCK_FIELD_IS_OBJECT;
1185 } else if (C.getLangOptions().CPlusPlus) {
1186 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1187 if (!record->hasTrivialDestructor())
1188 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001189 }
John McCall6b5a61b2011-02-07 10:33:21 +00001190
1191 if (!dtor && !flags) continue;
1192
1193 unsigned index = capture.getIndex();
1194 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1195
1196 // If there's an explicit copy expression, we do that.
1197 if (dtor) {
1198 CGF.PushDestructorCleanup(dtor, srcField);
1199
1200 // Otherwise we call _Block_object_dispose. It wouldn't be too
1201 // hard to just emit this as a cleanup if we wanted to make sure
1202 // that things were done in reverse.
1203 } else {
1204 llvm::Value *value = Builder.CreateLoad(srcField);
1205 value = Builder.CreateBitCast(value, PtrToInt8Ty);
1206 BuildBlockRelease(value, flags);
1207 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001208 }
1209
John McCall6b5a61b2011-02-07 10:33:21 +00001210 cleanups.ForceCleanup();
1211
Mike Stumpa4f668f2009-03-06 01:33:24 +00001212 CGF.FinishFunction();
1213
Owen Anderson3c4972d2009-07-29 18:54:39 +00001214 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001215}
1216
Mike Stumpee094222009-03-06 06:12:24 +00001217llvm::Constant *BlockFunction::
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001218GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag,
1219 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001220 QualType R = getContext().VoidTy;
1221
1222 FunctionArgList Args;
1223 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001224 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001225 ImplicitParamDecl::Create(getContext(), 0,
1226 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001227 getContext().getPointerType(getContext().VoidTy));
1228 Args.push_back(std::make_pair(Dst, Dst->getType()));
1229
1230 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001231 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001232 ImplicitParamDecl::Create(getContext(), 0,
1233 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001234 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001235 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Mike Stump45031c02009-03-06 02:29:21 +00001237 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001238 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001239
Mike Stump45031c02009-03-06 02:29:21 +00001240 CodeGenTypes &Types = CGM.getTypes();
1241 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1242
Mike Stump3899a7f2009-06-05 23:26:36 +00001243 // FIXME: We'd like to put these into a mergable by content, with
1244 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001245 llvm::Function *Fn =
1246 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001247 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001248
1249 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001250 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001251
1252 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1253 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001254 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001255 SC_Static,
1256 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001257 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001258 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001259
1260 // dst->x
1261 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001262 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001263 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001264 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001265 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001266
1267 // src->x
1268 V = CGF.GetAddrOfLocalVar(Src);
1269 V = Builder.CreateLoad(V);
1270 V = Builder.CreateBitCast(V, T);
1271 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001272
1273 if (flag & BLOCK_HAS_CXX_OBJ) {
1274 assert (BD && "VarDecl is null - GeneratebyrefCopyHelperFunction");
1275 llvm::Value *SrcObj = V;
1276 CGF.EmitSynthesizedCXXCopyCtor(DstObj, SrcObj,
1277 getContext().getBlockVarCopyInits(BD));
1278 }
1279 else {
1280 DstObj = Builder.CreateBitCast(DstObj, PtrToInt8Ty);
1281 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1282 llvm::Value *SrcObj = Builder.CreateLoad(V);
1283 flag |= BLOCK_BYREF_CALLER;
1284 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1285 llvm::Value *F = CGM.getBlockObjectAssign();
1286 Builder.CreateCall3(F, DstObj, SrcObj, N);
1287 }
1288
Mike Stump45031c02009-03-06 02:29:21 +00001289 CGF.FinishFunction();
1290
Owen Anderson3c4972d2009-07-29 18:54:39 +00001291 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001292}
1293
Mike Stump1851b682009-03-06 04:53:30 +00001294llvm::Constant *
1295BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001296 int flag,
1297 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001298 QualType R = getContext().VoidTy;
1299
1300 FunctionArgList Args;
1301 // FIXME: This leaks
1302 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001303 ImplicitParamDecl::Create(getContext(), 0,
1304 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001305 getContext().getPointerType(getContext().VoidTy));
1306
1307 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Mike Stump45031c02009-03-06 02:29:21 +00001309 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001310 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001311
Mike Stump45031c02009-03-06 02:29:21 +00001312 CodeGenTypes &Types = CGM.getTypes();
1313 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1314
Mike Stump3899a7f2009-06-05 23:26:36 +00001315 // FIXME: We'd like to put these into a mergable by content, with
1316 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001317 llvm::Function *Fn =
1318 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001319 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001320 &CGM.getModule());
1321
1322 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001323 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001324
1325 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1326 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001327 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001328 SC_Static,
1329 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001330 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001331 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001332
1333 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001334 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001335 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001336 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001337 if (flag & BLOCK_HAS_CXX_OBJ) {
1338 EHScopeStack::stable_iterator CleanupDepth = CGF.EHStack.stable_begin();
1339 assert (BD && "VarDecl is null - GeneratebyrefDestroyHelperFunction");
1340 QualType ClassTy = BD->getType();
1341 CGF.PushDestructorCleanup(ClassTy, V);
1342 CGF.PopCleanupBlocks(CleanupDepth);
1343 }
1344 else {
1345 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1346 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001347
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001348 flag |= BLOCK_BYREF_CALLER;
1349 BuildBlockRelease(V, flag);
1350 }
Mike Stump45031c02009-03-06 02:29:21 +00001351 CGF.FinishFunction();
1352
Owen Anderson3c4972d2009-07-29 18:54:39 +00001353 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001354}
1355
Mike Stumpee094222009-03-06 06:12:24 +00001356llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001357 uint32_t flags,
1358 unsigned align,
1359 const VarDecl *var) {
Chris Lattner10976d92009-12-05 08:21:30 +00001360 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001361 // pointer alignment, as we always have at least that much alignment to begin
1362 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001363 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001364
Mike Stump3899a7f2009-06-05 23:26:36 +00001365 // As an optimization, we only generate a single function of each kind we
1366 // might need. We need a different one for each alignment and for each
1367 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001368 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001369 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001370 if (Entry)
1371 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001372 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001373 CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001374}
1375
Mike Stump1851b682009-03-06 04:53:30 +00001376llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001377 uint32_t flags,
1378 unsigned align,
1379 const VarDecl *var) {
Mike Stump3899a7f2009-06-05 23:26:36 +00001380 // All alignments below that of pointer alignment collpase down to just
1381 // pointer alignment, as we always have at least that much alignment to begin
1382 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001383 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001384
Mike Stump3899a7f2009-06-05 23:26:36 +00001385 // As an optimization, we only generate a single function of each kind we
1386 // might need. We need a different one for each alignment and for each
1387 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001388 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001389 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001390 if (Entry)
1391 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001392 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001393 CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001394}
1395
John McCall6b5a61b2011-02-07 10:33:21 +00001396void BlockFunction::BuildBlockRelease(llvm::Value *V, uint32_t flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001397 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001398 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001399 V = Builder.CreateBitCast(V, PtrToInt8Ty);
John McCall6b5a61b2011-02-07 10:33:21 +00001400 N = llvm::ConstantInt::get(CGF.Int32Ty, flags);
Mike Stump797b6322009-03-05 01:23:13 +00001401 Builder.CreateCall2(F, V, N);
1402}
Mike Stump00470a12009-03-05 08:32:30 +00001403
1404ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001405
1406BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1407 CGBuilderTy &B)
John McCall6b5a61b2011-02-07 10:33:21 +00001408 : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf),
1409 BlockInfo(0), BlockPointer(0), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001410 PtrToInt8Ty = llvm::PointerType::getUnqual(
1411 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001412}