blob: e78e175a5a7bdd8d75585ff9f2bba3b12f772f7a [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
John McCall461c9c12011-02-08 03:07:00 +0000204/// Determines if the given record type has a mutable field.
205static bool hasMutableField(const CXXRecordDecl *record) {
206 for (CXXRecordDecl::field_iterator
207 i = record->field_begin(), e = record->field_end(); i != e; ++i)
208 if ((*i)->isMutable())
209 return true;
210
211 for (CXXRecordDecl::base_class_const_iterator
212 i = record->bases_begin(), e = record->bases_end(); i != e; ++i) {
213 const RecordType *record = i->getType()->castAs<RecordType>();
214 if (hasMutableField(cast<CXXRecordDecl>(record->getDecl())))
215 return true;
216 }
217
218 return false;
219}
220
221/// Determines if the given type is safe for constant capture in C++.
222static bool isSafeForCXXConstantCapture(QualType type) {
223 const RecordType *recordType =
224 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
225
226 // Only records can be unsafe.
227 if (!recordType) return true;
228
229 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
230
231 // Maintain semantics for classes with non-trivial dtors or copy ctors.
232 if (!record->hasTrivialDestructor()) return false;
233 if (!record->hasTrivialCopyConstructor()) return false;
234
235 // Otherwise, we just have to make sure there aren't any mutable
236 // fields that might have changed since initialization.
237 return !hasMutableField(record);
238}
239
John McCall6b5a61b2011-02-07 10:33:21 +0000240/// It is illegal to modify a const object after initialization.
241/// Therefore, if a const object has a constant initializer, we don't
242/// actually need to keep storage for it in the block; we'll just
243/// rematerialize it at the start of the block function. This is
244/// acceptable because we make no promises about address stability of
245/// captured variables.
246static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
247 const VarDecl *var) {
248 QualType type = var->getType();
249
250 // We can only do this if the variable is const.
251 if (!type.isConstQualified()) return 0;
252
John McCall461c9c12011-02-08 03:07:00 +0000253 // Furthermore, in C++ we have to worry about mutable fields:
254 // C++ [dcl.type.cv]p4:
255 // Except that any class member declared mutable can be
256 // modified, any attempt to modify a const object during its
257 // lifetime results in undefined behavior.
258 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000259 return 0;
260
261 // If the variable doesn't have any initializer (shouldn't this be
262 // invalid?), it's not clear what we should do. Maybe capture as
263 // zero?
264 const Expr *init = var->getInit();
265 if (!init) return 0;
266
267 return CGM.EmitConstantExpr(init, var->getType());
268}
269
270/// Get the low bit of a nonzero character count. This is the
271/// alignment of the nth byte if the 0th byte is universally aligned.
272static CharUnits getLowBit(CharUnits v) {
273 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
274}
275
276static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
277 std::vector<const llvm::Type*> &elementTypes) {
278 ASTContext &C = CGM.getContext();
279
280 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
281 CharUnits ptrSize, ptrAlign, intSize, intAlign;
282 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
283 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
284
285 // Are there crazy embedded platforms where this isn't true?
286 assert(intSize <= ptrSize && "layout assumptions horribly violated");
287
288 CharUnits headerSize = ptrSize;
289 if (2 * intSize < ptrAlign) headerSize += ptrSize;
290 else headerSize += 2 * intSize;
291 headerSize += 2 * ptrSize;
292
293 info.BlockAlign = ptrAlign;
294 info.BlockSize = headerSize;
295
296 assert(elementTypes.empty());
297 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
298 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
299 elementTypes.push_back(i8p);
300 elementTypes.push_back(intTy);
301 elementTypes.push_back(intTy);
302 elementTypes.push_back(i8p);
303 elementTypes.push_back(CGM.getBlockDescriptorType());
304
305 assert(elementTypes.size() == BlockHeaderSize);
306}
307
308/// Compute the layout of the given block. Attempts to lay the block
309/// out with minimal space requirements.
310static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
311 ASTContext &C = CGM.getContext();
312 const BlockDecl *block = info.getBlockDecl();
313
314 std::vector<const llvm::Type*> elementTypes;
315 initializeForBlockHeader(CGM, info, elementTypes);
316
317 if (!block->hasCaptures()) {
318 info.StructureType =
319 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
320 info.CanBeGlobal = true;
321 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000322 }
Mike Stump00470a12009-03-05 08:32:30 +0000323
John McCall6b5a61b2011-02-07 10:33:21 +0000324 // Collect the layout chunks.
325 llvm::SmallVector<BlockLayoutChunk, 16> layout;
326 layout.reserve(block->capturesCXXThis() +
327 (block->capture_end() - block->capture_begin()));
328
329 CharUnits maxFieldAlign;
330
331 // First, 'this'.
332 if (block->capturesCXXThis()) {
333 const DeclContext *DC = block->getDeclContext();
334 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
335 ;
336 QualType thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
337
338 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
339 std::pair<CharUnits,CharUnits> tinfo
340 = CGM.getContext().getTypeInfoInChars(thisType);
341 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
342
343 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
344 }
345
346 // Next, all the block captures.
347 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
348 ce = block->capture_end(); ci != ce; ++ci) {
349 const VarDecl *variable = ci->getVariable();
350
351 if (ci->isByRef()) {
352 // We have to copy/dispose of the __block reference.
353 info.NeedsCopyDispose = true;
354
355 // Also note that it's weak for GC purposes.
356 if (variable->getType().isObjCGCWeak())
357 info.HasWeakBlockVariable = true;
358
359 // Just use void* instead of a pointer to the byref type.
360 QualType byRefPtrTy = C.VoidPtrTy;
361
362 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
363 std::pair<CharUnits,CharUnits> tinfo
364 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
365 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
366
367 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
368 &*ci, llvmType));
369 continue;
370 }
371
372 // Otherwise, build a layout chunk with the size and alignment of
373 // the declaration.
374 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
375 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
376 continue;
377 }
378
379 // Block pointers require copy/dispose.
380 if (variable->getType()->isBlockPointerType()) {
381 info.NeedsCopyDispose = true;
382
383 // So do Objective-C pointers.
384 } else if (variable->getType()->isObjCObjectPointerType() ||
385 C.isObjCNSObjectType(variable->getType())) {
386 info.NeedsCopyDispose = true;
387
388 // So do types that require non-trivial copy construction.
389 } else if (ci->hasCopyExpr()) {
390 info.NeedsCopyDispose = true;
391 info.HasCXXObject = true;
392
393 // And so do types with destructors.
394 } else if (CGM.getLangOptions().CPlusPlus) {
395 if (const CXXRecordDecl *record =
396 variable->getType()->getAsCXXRecordDecl()) {
397 if (!record->hasTrivialDestructor()) {
398 info.HasCXXObject = true;
399 info.NeedsCopyDispose = true;
400 }
401 }
402 }
403
404 CharUnits size = C.getTypeSizeInChars(variable->getType());
405 CharUnits align = C.getDeclAlign(variable);
406 maxFieldAlign = std::max(maxFieldAlign, align);
407
408 const llvm::Type *llvmType =
409 CGM.getTypes().ConvertTypeForMem(variable->getType());
410
411 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
412 }
413
414 // If that was everything, we're done here.
415 if (layout.empty()) {
416 info.StructureType =
417 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
418 info.CanBeGlobal = true;
419 return;
420 }
421
422 // Sort the layout by alignment. We have to use a stable sort here
423 // to get reproducible results. There should probably be an
424 // llvm::array_pod_stable_sort.
425 std::stable_sort(layout.begin(), layout.end());
426
427 CharUnits &blockSize = info.BlockSize;
428 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
429
430 // Assuming that the first byte in the header is maximally aligned,
431 // get the alignment of the first byte following the header.
432 CharUnits endAlign = getLowBit(blockSize);
433
434 // If the end of the header isn't satisfactorily aligned for the
435 // maximum thing, look for things that are okay with the header-end
436 // alignment, and keep appending them until we get something that's
437 // aligned right. This algorithm is only guaranteed optimal if
438 // that condition is satisfied at some point; otherwise we can get
439 // things like:
440 // header // next byte has alignment 4
441 // something_with_size_5; // next byte has alignment 1
442 // something_with_alignment_8;
443 // which has 7 bytes of padding, as opposed to the naive solution
444 // which might have less (?).
445 if (endAlign < maxFieldAlign) {
446 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
447 li = layout.begin() + 1, le = layout.end();
448
449 // Look for something that the header end is already
450 // satisfactorily aligned for.
451 for (; li != le && endAlign < li->Alignment; ++li)
452 ;
453
454 // If we found something that's naturally aligned for the end of
455 // the header, keep adding things...
456 if (li != le) {
457 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
458 for (; li != le; ++li) {
459 assert(endAlign >= li->Alignment);
460
461 li->setIndex(info, elementTypes.size());
462 elementTypes.push_back(li->Type);
463 blockSize += li->Size;
464 endAlign = getLowBit(blockSize);
465
466 // ...until we get to the alignment of the maximum field.
467 if (endAlign >= maxFieldAlign)
468 break;
469 }
470
471 // Don't re-append everything we just appended.
472 layout.erase(first, li);
473 }
474 }
475
476 // At this point, we just have to add padding if the end align still
477 // isn't aligned right.
478 if (endAlign < maxFieldAlign) {
479 CharUnits padding = maxFieldAlign - endAlign;
480
481 const llvm::Type *i8 = llvm::IntegerType::get(CGM.getLLVMContext(), 8);
482 elementTypes.push_back(llvm::ArrayType::get(i8, padding.getQuantity()));
483 blockSize += padding;
484
485 endAlign = getLowBit(blockSize);
486 assert(endAlign >= maxFieldAlign);
487 }
488
489 // Slam everything else on now. This works because they have
490 // strictly decreasing alignment and we expect that size is always a
491 // multiple of alignment.
492 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
493 li = layout.begin(), le = layout.end(); li != le; ++li) {
494 assert(endAlign >= li->Alignment);
495 li->setIndex(info, elementTypes.size());
496 elementTypes.push_back(li->Type);
497 blockSize += li->Size;
498 endAlign = getLowBit(blockSize);
499 }
500
501 info.StructureType =
502 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
503}
504
505/// Emit a block literal expression in the current function.
506llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
507 std::string Name = CurFn->getName();
508 CGBlockInfo blockInfo(blockExpr, Name.c_str());
509
510 // Compute information about the layout, etc., of this block.
511 computeBlockInfo(CGM, blockInfo);
512
513 // Using that metadata, generate the actual block function.
514 llvm::Constant *blockFn
515 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
516 CurFuncDecl, LocalDeclMap);
517 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
518
519 // If there is nothing to capture, we can emit this as a global block.
520 if (blockInfo.CanBeGlobal)
521 return buildGlobalBlock(CGM, blockInfo, blockFn);
522
523 // Otherwise, we have to emit this as a local block.
524
525 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
526 isa = llvm::ConstantExpr::getBitCast(isa, PtrToInt8Ty);
527
528 // Build the block descriptor.
529 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
530
531 const llvm::Type *intTy = ConvertType(getContext().IntTy);
532
533 llvm::AllocaInst *blockAddr =
534 CreateTempAlloca(blockInfo.StructureType, "block");
535 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
536
537 // Compute the initial on-stack block flags.
538 unsigned int flags = BLOCK_HAS_SIGNATURE;
539 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
540 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
541 flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(), flags);
542
543 // Initialize the block literal.
544 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
545 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags),
546 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
547 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
548 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
549 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
550 "block.invoke"));
551 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
552 "block.descriptor"));
553
554 // Finally, capture all the values into the block.
555 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
556
557 // First, 'this'.
558 if (blockDecl->capturesCXXThis()) {
559 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
560 blockInfo.CXXThisIndex,
561 "block.captured-this.addr");
562 Builder.CreateStore(LoadCXXThis(), addr);
563 }
564
565 // Next, captured variables.
566 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
567 ce = blockDecl->capture_end(); ci != ce; ++ci) {
568 const VarDecl *variable = ci->getVariable();
569 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
570
571 // Ignore constant captures.
572 if (capture.isConstant()) continue;
573
574 QualType type = variable->getType();
575
576 // This will be a [[type]]*, except that a byref entry will just be
577 // an i8**.
578 llvm::Value *blockField =
579 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
580 "block.captured");
581
582 // Compute the address of the thing we're going to move into the
583 // block literal.
584 llvm::Value *src;
585 if (ci->isNested()) {
586 // We need to use the capture from the enclosing block.
587 const CGBlockInfo::Capture &enclosingCapture =
588 BlockInfo->getCapture(variable);
589
590 // This is a [[type]]*, except that a byref entry wil just be an i8**.
591 src = Builder.CreateStructGEP(LoadBlockStruct(),
592 enclosingCapture.getIndex(),
593 "block.capture.addr");
594 } else {
595 // This is a [[type]]*.
596 src = LocalDeclMap[variable];
597 }
598
599 // For byrefs, we just write the pointer to the byref struct into
600 // the block field. There's no need to chase the forwarding
601 // pointer at this point, since we're building something that will
602 // live a shorter life than the stack byref anyway.
603 if (ci->isByRef()) {
604 // Get an i8* that points to the byref struct.
605 if (ci->isNested())
606 src = Builder.CreateLoad(src, "byref.capture");
607 else
608 src = Builder.CreateBitCast(src, PtrToInt8Ty);
609
610 // Write that i8* into the capture field.
611 Builder.CreateStore(src, blockField);
612
613 // If we have a copy constructor, evaluate that into the block field.
614 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
615 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
616
617 // If it's a reference variable, copy the reference into the block field.
618 } else if (type->isReferenceType()) {
619 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
620
621 // Otherwise, fake up a POD copy into the block field.
622 } else {
John McCallbb699b02011-02-07 18:37:40 +0000623 // We use one of these or the other depending on whether the
624 // reference is nested.
625 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
626 SourceLocation());
627 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
628 VK_LValue, SourceLocation(), /*byref*/ false);
629
630 Expr *declRef =
631 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
632
John McCall6b5a61b2011-02-07 10:33:21 +0000633 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000634 declRef, VK_RValue);
John McCall6b5a61b2011-02-07 10:33:21 +0000635 EmitAnyExprToMem(&l2r, blockField, /*volatile*/ false, /*init*/ true);
636 }
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
650 // We must call objc_read_weak on the block literal itself if it closes
651 // on any __weak __block variables. For some reason.
John McCall6b5a61b2011-02-07 10:33:21 +0000652 if (blockInfo.HasWeakBlockVariable) {
653 const llvm::Type *OrigTy = result->getType();
John McCall711c52b2011-01-05 12:14:39 +0000654
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000655 // Must cast argument to id*
656 const llvm::Type *ObjectPtrTy =
657 ConvertType(CGM.getContext().getObjCIdType());
658 const llvm::Type *PtrObjectPtrTy =
659 llvm::PointerType::getUnqual(ObjectPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000660 result = Builder.CreateBitCast(result, PtrObjectPtrTy);
661 result = CGM.getObjCRuntime().EmitObjCWeakRead(*this, result);
John McCall711c52b2011-01-05 12:14:39 +0000662
663 // Cast back to the original type.
John McCall6b5a61b2011-02-07 10:33:21 +0000664 result = Builder.CreateBitCast(result, OrigTy);
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000665 }
John McCall6b5a61b2011-02-07 10:33:21 +0000666 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000667}
668
669
Mike Stump2a998142009-03-04 18:17:45 +0000670const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000671 if (BlockDescriptorType)
672 return BlockDescriptorType;
673
Mike Stumpa5448542009-02-13 15:32:32 +0000674 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000675 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000676
Mike Stumpab695142009-02-13 15:16:56 +0000677 // struct __block_descriptor {
678 // unsigned long reserved;
679 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000680 //
681 // // later, the following will be added
682 //
683 // struct {
684 // void (*copyHelper)();
685 // void (*copyHelper)();
686 // } helpers; // !!! optional
687 //
688 // const char *signature; // the block signature
689 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000690 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000691 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
692 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000693 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000694 NULL);
695
696 getModule().addTypeName("struct.__block_descriptor",
697 BlockDescriptorType);
698
John McCall6b5a61b2011-02-07 10:33:21 +0000699 // Now form a pointer to that.
700 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000701 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000702}
703
Mike Stump2a998142009-03-04 18:17:45 +0000704const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000705 if (GenericBlockLiteralType)
706 return GenericBlockLiteralType;
707
John McCall6b5a61b2011-02-07 10:33:21 +0000708 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000709
Mike Stump7cbb3602009-02-13 16:01:35 +0000710 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
711 getTypes().ConvertType(getContext().IntTy));
712
Mike Stump9b8a7972009-02-13 15:25:34 +0000713 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000714 // void *__isa;
715 // int __flags;
716 // int __reserved;
717 // void (*__invoke)(void *);
718 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000719 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000720 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000721 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000722 IntTy,
723 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000724 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000725 BlockDescPtrTy,
726 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000727
Mike Stump9b8a7972009-02-13 15:25:34 +0000728 getModule().addTypeName("struct.__block_literal_generic",
729 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000730
Mike Stump9b8a7972009-02-13 15:25:34 +0000731 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000732}
733
Mike Stumpbd65cac2009-02-19 01:01:04 +0000734
Anders Carlssona1736c02009-12-24 21:13:40 +0000735RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
736 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000737 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000738 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000739
Anders Carlssonacfde802009-02-12 00:39:25 +0000740 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
741
742 // Get a pointer to the generic block literal.
743 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000744 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000745
746 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000747 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000748 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
749
750 // Get the function pointer from the literal.
751 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000752
Mike Stumpa5448542009-02-13 15:32:32 +0000753 BlockLiteral =
754 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000755 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000756 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000757
Anders Carlssonacfde802009-02-12 00:39:25 +0000758 // Add the block literal.
759 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
760 CallArgList Args;
761 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000762
Anders Carlsson782f3972009-04-08 23:13:16 +0000763 QualType FnType = BPT->getPointeeType();
764
Anders Carlssonacfde802009-02-12 00:39:25 +0000765 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000766 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000767 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000768
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000769 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000770 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000771
John McCall04a67a62010-02-05 21:31:56 +0000772 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
773 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000774
Mike Stump1eb44332009-09-09 15:08:12 +0000775 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000776 CGM.getTypes().getFunctionInfo(ResultType, Args,
777 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000779 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000780 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000781 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Owen Anderson96e0fc72009-07-29 22:16:19 +0000783 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000784 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Anders Carlssonacfde802009-02-12 00:39:25 +0000786 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000787 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000788}
Anders Carlssond5cab542009-02-12 17:55:02 +0000789
John McCall6b5a61b2011-02-07 10:33:21 +0000790llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
791 bool isByRef) {
792 assert(BlockInfo && "evaluating block ref without block information?");
793 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 // Handle constant captures.
796 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000797
John McCall6b5a61b2011-02-07 10:33:21 +0000798 llvm::Value *addr =
799 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
800 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000801
John McCall6b5a61b2011-02-07 10:33:21 +0000802 if (isByRef) {
803 // addr should be a void** right now. Load, then cast the result
804 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000805
John McCall6b5a61b2011-02-07 10:33:21 +0000806 addr = Builder.CreateLoad(addr);
807 const llvm::PointerType *byrefPointerType
808 = llvm::PointerType::get(BuildByRefType(variable), 0);
809 addr = Builder.CreateBitCast(addr, byrefPointerType,
810 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000811
John McCall6b5a61b2011-02-07 10:33:21 +0000812 // Follow the forwarding pointer.
813 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
814 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000815
John McCall6b5a61b2011-02-07 10:33:21 +0000816 // Cast back to byref* and GEP over to the actual object.
817 addr = Builder.CreateBitCast(addr, byrefPointerType);
818 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
819 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000820 }
821
John McCall6b5a61b2011-02-07 10:33:21 +0000822 if (variable->getType()->isReferenceType())
823 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000824
John McCall6b5a61b2011-02-07 10:33:21 +0000825 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000826}
827
Mike Stump67a64482009-02-14 22:16:35 +0000828llvm::Constant *
John McCall6b5a61b2011-02-07 10:33:21 +0000829BlockModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
830 const char *name) {
831 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000832
John McCall6b5a61b2011-02-07 10:33:21 +0000833 // Compute information about the layout, etc., of this block.
834 computeBlockInfo(CGM, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000835
John McCall6b5a61b2011-02-07 10:33:21 +0000836 // Using that metadata, generate the actual block function.
837 llvm::Constant *blockFn;
838 {
839 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
840 blockFn = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(),
841 blockInfo,
842 0, LocalDeclMap);
843 }
844 blockFn = llvm::ConstantExpr::getBitCast(blockFn, PtrToInt8Ty);
Mike Stumpa5448542009-02-13 15:32:32 +0000845
John McCall6b5a61b2011-02-07 10:33:21 +0000846 return buildGlobalBlock(CGM, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000847}
848
John McCall6b5a61b2011-02-07 10:33:21 +0000849static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
850 const CGBlockInfo &blockInfo,
851 llvm::Constant *blockFn) {
852 assert(blockInfo.CanBeGlobal);
853
854 // Generate the constants for the block literal initializer.
855 llvm::Constant *fields[BlockHeaderSize];
856
857 // isa
858 fields[0] = CGM.getNSConcreteGlobalBlock();
859
860 // __flags
861 unsigned flags = computeBlockFlag(CGM, blockInfo.getBlockExpr(),
862 BlockBase::BLOCK_IS_GLOBAL |
863 BlockBase::BLOCK_HAS_SIGNATURE);
864 const llvm::Type *intTy = CGM.getTypes().ConvertType(CGM.getContext().IntTy);
865 fields[1] = llvm::ConstantInt::get(intTy, flags);
866
867 // Reserved
868 fields[2] = llvm::Constant::getNullValue(intTy);
869
870 // Function
871 fields[3] = blockFn;
872
873 // Descriptor
874 fields[4] = buildBlockDescriptor(CGM, blockInfo);
875
876 llvm::Constant *init =
877 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
878 /*packed*/ false);
879
880 llvm::GlobalVariable *literal =
881 new llvm::GlobalVariable(CGM.getModule(),
882 init->getType(),
883 /*constant*/ true,
884 llvm::GlobalVariable::InternalLinkage,
885 init,
886 "__block_literal_global");
887 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
888
889 // Return a constant of the appropriately-casted type.
890 const llvm::Type *requiredType =
891 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
892 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000893}
894
Mike Stump00470a12009-03-05 08:32:30 +0000895llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000896CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
897 const CGBlockInfo &blockInfo,
898 const Decl *outerFnDecl,
899 const DeclMapTy &ldm) {
900 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000901
John McCall6b5a61b2011-02-07 10:33:21 +0000902 DebugInfo = CGM.getDebugInfo();
903 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Mike Stump7f28a9c2009-03-13 23:34:28 +0000905 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000906 // to be local to this function as well, in case they're directly
907 // referenced in a block.
908 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
909 const VarDecl *var = dyn_cast<VarDecl>(i->first);
910 if (var && !var->hasLocalStorage())
911 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000912 }
913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000915
John McCall6b5a61b2011-02-07 10:33:21 +0000916 // Build the argument list.
917 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000918
John McCall6b5a61b2011-02-07 10:33:21 +0000919 // The first argument is the block pointer. Just take it as a void*
920 // and cast it later.
921 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000922 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000923
John McCall6b5a61b2011-02-07 10:33:21 +0000924 // FIXME: this leaks, and we only need it very temporarily.
925 ImplicitParamDecl *selfDecl =
926 ImplicitParamDecl::Create(getContext(),
927 const_cast<BlockDecl*>(blockDecl),
928 SourceLocation(), II, selfTy);
929 args.push_back(std::make_pair(selfDecl, selfTy));
Mike Stumpea26cb52009-10-21 03:49:08 +0000930
John McCall6b5a61b2011-02-07 10:33:21 +0000931 // Now add the rest of the parameters.
932 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
933 e = blockDecl->param_end(); i != e; ++i)
934 args.push_back(std::make_pair(*i, (*i)->getType()));
John McCallea1471e2010-05-20 01:18:31 +0000935
John McCall6b5a61b2011-02-07 10:33:21 +0000936 // Create the function declaration.
937 const FunctionProtoType *fnType =
938 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
939 const CGFunctionInfo &fnInfo =
940 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
941 fnType->getExtInfo());
942 const llvm::FunctionType *fnLLVMType =
943 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000944
John McCall6b5a61b2011-02-07 10:33:21 +0000945 MangleBuffer name;
946 CGM.getBlockMangledName(GD, name, blockDecl);
947 llvm::Function *fn =
948 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
949 name.getString(), &CGM.getModule());
950 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000951
John McCall6b5a61b2011-02-07 10:33:21 +0000952 // Begin generating the function.
953 StartFunction(blockDecl, fnType->getResultType(), fn, args,
954 blockInfo.getBlockExpr()->getBody()->getLocEnd());
955 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000956
John McCall6b5a61b2011-02-07 10:33:21 +0000957 // Okay. Undo some of what StartFunction did. We really don't need
958 // an alloca for the block address; in theory we could remove it,
959 // but that might do unpleasant things to debug info.
960 llvm::AllocaInst *blockAddrAlloca
961 = cast<llvm::AllocaInst>(LocalDeclMap[selfDecl]);
962 llvm::Value *blockAddr = Builder.CreateLoad(blockAddrAlloca);
963 BlockPointer = Builder.CreateBitCast(blockAddr,
964 blockInfo.StructureType->getPointerTo(),
965 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000966
John McCallea1471e2010-05-20 01:18:31 +0000967 // If we have a C++ 'this' reference, go ahead and force it into
968 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000969 if (blockDecl->capturesCXXThis()) {
970 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
971 blockInfo.CXXThisIndex,
972 "block.captured-this");
973 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000974 }
975
John McCall6b5a61b2011-02-07 10:33:21 +0000976 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
977 // appease it.
978 if (const ObjCMethodDecl *method
979 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
980 const VarDecl *self = method->getSelfDecl();
981
982 // There might not be a capture for 'self', but if there is...
983 if (blockInfo.Captures.count(self)) {
984 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
985 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
986 capture.getIndex(),
987 "block.captured-self");
988 LocalDeclMap[self] = selfAddr;
989 }
990 }
991
992 // Also force all the constant captures.
993 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
994 ce = blockDecl->capture_end(); ci != ce; ++ci) {
995 const VarDecl *variable = ci->getVariable();
996 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
997 if (!capture.isConstant()) continue;
998
999 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1000
1001 llvm::AllocaInst *alloca =
1002 CreateMemTemp(variable->getType(), "block.captured-const");
1003 alloca->setAlignment(align);
1004
1005 Builder.CreateStore(capture.getConstant(), alloca, align);
1006
1007 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001008 }
1009
Mike Stumpb289b3f2009-10-01 22:29:41 +00001010 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1011 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1012 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1013 --entry_ptr;
1014
John McCall6b5a61b2011-02-07 10:33:21 +00001015 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001016
Mike Stumpde8c5c72009-10-01 00:27:30 +00001017 // Remember where we were...
1018 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001019
Mike Stumpde8c5c72009-10-01 00:27:30 +00001020 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001021 ++entry_ptr;
1022 Builder.SetInsertPoint(entry, entry_ptr);
1023
John McCall6b5a61b2011-02-07 10:33:21 +00001024 // Emit debug information for all the BlockDeclRefDecls.
1025 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001026 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001027 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1028 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1029 const VarDecl *variable = ci->getVariable();
1030 DI->setLocation(variable->getLocation());
1031
1032 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1033 if (capture.isConstant()) {
1034 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1035 Builder);
1036 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001037 }
John McCall6b5a61b2011-02-07 10:33:21 +00001038
1039 DI->EmitDeclareOfBlockDeclRefVariable(variable, blockAddrAlloca,
1040 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001041 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001042 }
John McCall6b5a61b2011-02-07 10:33:21 +00001043
Mike Stumpde8c5c72009-10-01 00:27:30 +00001044 // And resume where we left off.
1045 if (resume == 0)
1046 Builder.ClearInsertionPoint();
1047 else
1048 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001049
John McCall6b5a61b2011-02-07 10:33:21 +00001050 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001053}
Mike Stumpa99038c2009-02-28 09:07:16 +00001054
John McCall6b5a61b2011-02-07 10:33:21 +00001055/*
1056 notes.push_back(HelperInfo());
1057 HelperInfo &note = notes.back();
1058 note.index = capture.getIndex();
1059 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1060 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001061
John McCall6b5a61b2011-02-07 10:33:21 +00001062 if (ci->isByRef()) {
1063 note.flag = BLOCK_FIELD_IS_BYREF;
1064 if (type.isObjCGCWeak())
1065 note.flag |= BLOCK_FIELD_IS_WEAK;
1066 } else if (type->isBlockPointerType()) {
1067 note.flag = BLOCK_FIELD_IS_BLOCK;
1068 } else {
1069 note.flag = BLOCK_FIELD_IS_OBJECT;
1070 }
1071 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001072
Mike Stump00470a12009-03-05 08:32:30 +00001073
Mike Stumpa99038c2009-02-28 09:07:16 +00001074
Mike Stumpdab514f2009-03-04 03:23:46 +00001075
Mike Stumpa4f668f2009-03-06 01:33:24 +00001076
John McCall6b5a61b2011-02-07 10:33:21 +00001077llvm::Constant *
1078BlockFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
1079 ASTContext &C = getContext();
1080
1081 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001082 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001083 ImplicitParamDecl *dstDecl =
1084 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1085 args.push_back(std::make_pair(dstDecl, dstDecl->getType()));
1086 ImplicitParamDecl *srcDecl =
1087 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1088 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Mike Stumpa4f668f2009-03-06 01:33:24 +00001090 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001091 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001092
John McCall6b5a61b2011-02-07 10:33:21 +00001093 // FIXME: it would be nice if these were mergeable with things with
1094 // identical semantics.
1095 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001096
1097 llvm::Function *Fn =
1098 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001099 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001100
1101 IdentifierInfo *II
1102 = &CGM.getContext().Idents.get("__copy_helper_block_");
1103
John McCall6b5a61b2011-02-07 10:33:21 +00001104 FunctionDecl *FD = FunctionDecl::Create(C,
1105 C.getTranslationUnitDecl(),
1106 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001107 SC_Static,
1108 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001109 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001110 true);
John McCall6b5a61b2011-02-07 10:33:21 +00001111 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001112
John McCall6b5a61b2011-02-07 10:33:21 +00001113 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001114
John McCall6b5a61b2011-02-07 10:33:21 +00001115 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1116 src = CGF.Builder.CreateLoad(src);
1117 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001118
John McCall6b5a61b2011-02-07 10:33:21 +00001119 llvm::Value *dst = CGF.GetAddrOfLocalVar(dstDecl);
1120 dst = CGF.Builder.CreateLoad(dst);
1121 dst = CGF.Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001122
John McCall6b5a61b2011-02-07 10:33:21 +00001123 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1126 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1127 const VarDecl *variable = ci->getVariable();
1128 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001129
John McCall6b5a61b2011-02-07 10:33:21 +00001130 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1131 if (capture.isConstant()) continue;
1132
1133 const Expr *copyExpr = ci->getCopyExpr();
1134 unsigned flags = 0;
1135
1136 if (copyExpr) {
1137 assert(!ci->isByRef());
1138 // don't bother computing flags
1139 } else if (ci->isByRef()) {
1140 flags = BLOCK_FIELD_IS_BYREF;
1141 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1142 } else if (type->isBlockPointerType()) {
1143 flags = BLOCK_FIELD_IS_BLOCK;
1144 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1145 flags = BLOCK_FIELD_IS_OBJECT;
1146 }
1147
1148 if (!copyExpr && !flags) continue;
1149
1150 unsigned index = capture.getIndex();
1151 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1152 llvm::Value *dstField = CGF.Builder.CreateStructGEP(dst, index);
1153
1154 // If there's an explicit copy expression, we do that.
1155 if (copyExpr) {
1156 CGF.EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
1157 } else {
1158 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
1159 srcValue = Builder.CreateBitCast(srcValue, PtrToInt8Ty);
1160 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, PtrToInt8Ty);
1161 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1162 llvm::ConstantInt::get(CGF.Int32Ty, flags));
Mike Stump08920992009-03-07 02:35:30 +00001163 }
1164 }
1165
Mike Stumpa4f668f2009-03-06 01:33:24 +00001166 CGF.FinishFunction();
1167
Owen Anderson3c4972d2009-07-29 18:54:39 +00001168 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +00001169}
1170
John McCall6b5a61b2011-02-07 10:33:21 +00001171llvm::Constant *
1172BlockFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
1173 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001174
John McCall6b5a61b2011-02-07 10:33:21 +00001175 FunctionArgList args;
Mike Stumpa4f668f2009-03-06 01:33:24 +00001176 // FIXME: This leaks
John McCall6b5a61b2011-02-07 10:33:21 +00001177 ImplicitParamDecl *srcDecl =
1178 ImplicitParamDecl::Create(C, 0, SourceLocation(), 0, C.VoidPtrTy);
1179 args.push_back(std::make_pair(srcDecl, srcDecl->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Mike Stumpa4f668f2009-03-06 01:33:24 +00001181 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001182 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001183
Mike Stump3899a7f2009-06-05 23:26:36 +00001184 // FIXME: We'd like to put these into a mergable by content, with
1185 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001186 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001187
1188 llvm::Function *Fn =
1189 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001190 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001191
1192 IdentifierInfo *II
1193 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1194
John McCall6b5a61b2011-02-07 10:33:21 +00001195 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
1196 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001197 SC_Static,
1198 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001199 false, true);
John McCall6b5a61b2011-02-07 10:33:21 +00001200 CGF.StartFunction(FD, C.VoidTy, Fn, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001201
John McCall6b5a61b2011-02-07 10:33:21 +00001202 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001203
John McCall6b5a61b2011-02-07 10:33:21 +00001204 llvm::Value *src = CGF.GetAddrOfLocalVar(srcDecl);
1205 src = CGF.Builder.CreateLoad(src);
1206 src = CGF.Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001207
John McCall6b5a61b2011-02-07 10:33:21 +00001208 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1209
1210 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1211
1212 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1213 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1214 const VarDecl *variable = ci->getVariable();
1215 QualType type = variable->getType();
1216
1217 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1218 if (capture.isConstant()) continue;
1219
1220 unsigned flags = 0;
1221 const CXXDestructorDecl *dtor = 0;
1222
1223 if (ci->isByRef()) {
1224 flags = BLOCK_FIELD_IS_BYREF;
1225 if (type.isObjCGCWeak()) flags |= BLOCK_FIELD_IS_WEAK;
1226 } else if (type->isBlockPointerType()) {
1227 flags = BLOCK_FIELD_IS_BLOCK;
1228 } else if (type->isObjCObjectPointerType() || C.isObjCNSObjectType(type)) {
1229 flags = BLOCK_FIELD_IS_OBJECT;
1230 } else if (C.getLangOptions().CPlusPlus) {
1231 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
1232 if (!record->hasTrivialDestructor())
1233 dtor = record->getDestructor();
Mike Stump1edf6b62009-03-07 02:53:18 +00001234 }
John McCall6b5a61b2011-02-07 10:33:21 +00001235
1236 if (!dtor && !flags) continue;
1237
1238 unsigned index = capture.getIndex();
1239 llvm::Value *srcField = CGF.Builder.CreateStructGEP(src, index);
1240
1241 // If there's an explicit copy expression, we do that.
1242 if (dtor) {
1243 CGF.PushDestructorCleanup(dtor, srcField);
1244
1245 // Otherwise we call _Block_object_dispose. It wouldn't be too
1246 // hard to just emit this as a cleanup if we wanted to make sure
1247 // that things were done in reverse.
1248 } else {
1249 llvm::Value *value = Builder.CreateLoad(srcField);
1250 value = Builder.CreateBitCast(value, PtrToInt8Ty);
1251 BuildBlockRelease(value, flags);
1252 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001253 }
1254
John McCall6b5a61b2011-02-07 10:33:21 +00001255 cleanups.ForceCleanup();
1256
Mike Stumpa4f668f2009-03-06 01:33:24 +00001257 CGF.FinishFunction();
1258
Owen Anderson3c4972d2009-07-29 18:54:39 +00001259 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001260}
1261
Mike Stumpee094222009-03-06 06:12:24 +00001262llvm::Constant *BlockFunction::
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001263GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag,
1264 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001265 QualType R = getContext().VoidTy;
1266
1267 FunctionArgList Args;
1268 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001269 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001270 ImplicitParamDecl::Create(getContext(), 0,
1271 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001272 getContext().getPointerType(getContext().VoidTy));
1273 Args.push_back(std::make_pair(Dst, Dst->getType()));
1274
1275 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001276 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001277 ImplicitParamDecl::Create(getContext(), 0,
1278 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001279 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001280 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Mike Stump45031c02009-03-06 02:29:21 +00001282 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001283 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001284
Mike Stump45031c02009-03-06 02:29:21 +00001285 CodeGenTypes &Types = CGM.getTypes();
1286 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1287
Mike Stump3899a7f2009-06-05 23:26:36 +00001288 // FIXME: We'd like to put these into a mergable by content, with
1289 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001290 llvm::Function *Fn =
1291 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001292 "__Block_byref_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001293
1294 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001295 = &CGM.getContext().Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001296
1297 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1298 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001299 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001300 SC_Static,
1301 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001302 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001303 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001304
1305 // dst->x
1306 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001307 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001308 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001309 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001310 llvm::Value *DstObj = V;
Mike Stumpee094222009-03-06 06:12:24 +00001311
1312 // src->x
1313 V = CGF.GetAddrOfLocalVar(Src);
1314 V = Builder.CreateLoad(V);
1315 V = Builder.CreateBitCast(V, T);
1316 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001317
1318 if (flag & BLOCK_HAS_CXX_OBJ) {
1319 assert (BD && "VarDecl is null - GeneratebyrefCopyHelperFunction");
1320 llvm::Value *SrcObj = V;
1321 CGF.EmitSynthesizedCXXCopyCtor(DstObj, SrcObj,
1322 getContext().getBlockVarCopyInits(BD));
1323 }
1324 else {
1325 DstObj = Builder.CreateBitCast(DstObj, PtrToInt8Ty);
1326 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1327 llvm::Value *SrcObj = Builder.CreateLoad(V);
1328 flag |= BLOCK_BYREF_CALLER;
1329 llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1330 llvm::Value *F = CGM.getBlockObjectAssign();
1331 Builder.CreateCall3(F, DstObj, SrcObj, N);
1332 }
1333
Mike Stump45031c02009-03-06 02:29:21 +00001334 CGF.FinishFunction();
1335
Owen Anderson3c4972d2009-07-29 18:54:39 +00001336 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001337}
1338
Mike Stump1851b682009-03-06 04:53:30 +00001339llvm::Constant *
1340BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001341 int flag,
1342 const VarDecl *BD) {
Mike Stump45031c02009-03-06 02:29:21 +00001343 QualType R = getContext().VoidTy;
1344
1345 FunctionArgList Args;
1346 // FIXME: This leaks
1347 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001348 ImplicitParamDecl::Create(getContext(), 0,
1349 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001350 getContext().getPointerType(getContext().VoidTy));
1351
1352 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Mike Stump45031c02009-03-06 02:29:21 +00001354 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001355 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001356
Mike Stump45031c02009-03-06 02:29:21 +00001357 CodeGenTypes &Types = CGM.getTypes();
1358 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1359
Mike Stump3899a7f2009-06-05 23:26:36 +00001360 // FIXME: We'd like to put these into a mergable by content, with
1361 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001362 llvm::Function *Fn =
1363 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001364 "__Block_byref_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001365 &CGM.getModule());
1366
1367 IdentifierInfo *II
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001368 = &CGM.getContext().Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001369
1370 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1371 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001372 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001373 SC_Static,
1374 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001375 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001376 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001377
1378 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001379 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001380 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001381 V = Builder.CreateStructGEP(V, 6, "x");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001382 if (flag & BLOCK_HAS_CXX_OBJ) {
1383 EHScopeStack::stable_iterator CleanupDepth = CGF.EHStack.stable_begin();
1384 assert (BD && "VarDecl is null - GeneratebyrefDestroyHelperFunction");
1385 QualType ClassTy = BD->getType();
1386 CGF.PushDestructorCleanup(ClassTy, V);
1387 CGF.PopCleanupBlocks(CleanupDepth);
1388 }
1389 else {
1390 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1391 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001392
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001393 flag |= BLOCK_BYREF_CALLER;
1394 BuildBlockRelease(V, flag);
1395 }
Mike Stump45031c02009-03-06 02:29:21 +00001396 CGF.FinishFunction();
1397
Owen Anderson3c4972d2009-07-29 18:54:39 +00001398 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001399}
1400
Mike Stumpee094222009-03-06 06:12:24 +00001401llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001402 uint32_t flags,
1403 unsigned align,
1404 const VarDecl *var) {
Chris Lattner10976d92009-12-05 08:21:30 +00001405 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001406 // pointer alignment, as we always have at least that much alignment to begin
1407 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001408 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001409
Mike Stump3899a7f2009-06-05 23:26:36 +00001410 // As an optimization, we only generate a single function of each kind we
1411 // might need. We need a different one for each alignment and for each
1412 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001413 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001414 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001415 if (Entry)
1416 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001417 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001418 CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001419}
1420
Mike Stump1851b682009-03-06 04:53:30 +00001421llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
John McCall6b5a61b2011-02-07 10:33:21 +00001422 uint32_t flags,
1423 unsigned align,
1424 const VarDecl *var) {
Mike Stump3899a7f2009-06-05 23:26:36 +00001425 // All alignments below that of pointer alignment collpase down to just
1426 // pointer alignment, as we always have at least that much alignment to begin
1427 // with.
John McCall6b5a61b2011-02-07 10:33:21 +00001428 align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001429
Mike Stump3899a7f2009-06-05 23:26:36 +00001430 // As an optimization, we only generate a single function of each kind we
1431 // might need. We need a different one for each alignment and for each
1432 // setting of flags. We mix Align and flag to get the kind.
John McCall6b5a61b2011-02-07 10:33:21 +00001433 uint64_t Kind = (uint64_t)align*BLOCK_BYREF_CURRENT_MAX + flags;
Chris Lattner10976d92009-12-05 08:21:30 +00001434 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001435 if (Entry)
1436 return Entry;
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001437 return Entry =
John McCall6b5a61b2011-02-07 10:33:21 +00001438 CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flags, var);
Mike Stump45031c02009-03-06 02:29:21 +00001439}
1440
John McCall6b5a61b2011-02-07 10:33:21 +00001441void BlockFunction::BuildBlockRelease(llvm::Value *V, uint32_t flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001442 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001443 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001444 V = Builder.CreateBitCast(V, PtrToInt8Ty);
John McCall6b5a61b2011-02-07 10:33:21 +00001445 N = llvm::ConstantInt::get(CGF.Int32Ty, flags);
Mike Stump797b6322009-03-05 01:23:13 +00001446 Builder.CreateCall2(F, V, N);
1447}
Mike Stump00470a12009-03-05 08:32:30 +00001448
1449ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001450
1451BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1452 CGBuilderTy &B)
John McCall6b5a61b2011-02-07 10:33:21 +00001453 : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf),
1454 BlockInfo(0), BlockPointer(0), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001455 PtrToInt8Ty = llvm::PointerType::getUnqual(
1456 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001457}