blob: 3488f2edb7e657a55bc8e5dc9b235f1a61585839 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
Fariborz Jahanian1077e422011-06-28 23:51:26 +000028struct CallMemsetLocalBlockObject : EHScopeStack::Cleanup {
29 llvm::AllocaInst *BlockAddr;
30 CharUnits BlockSize;
31
32 CallMemsetLocalBlockObject(llvm::AllocaInst *blockAddr,
33 CharUnits blocSize)
34 : BlockAddr(blockAddr), BlockSize(blocSize) {}
35
36 void Emit(CodeGenFunction &CGF, bool isForEH) {
37 CGF.Builder.CreateMemSet(BlockAddr,
38 llvm::ConstantInt::get(CGF.Int8Ty, 0xCD),
39 BlockSize.getQuantity(),
40 BlockAddr->getAlignment());
41 }
42};
43
John McCall6b5a61b2011-02-07 10:33:21 +000044CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
45 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall64cd2322011-03-09 08:39:33 +000046 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000047
48 // Skip asm prefix, if any.
49 if (Name && Name[0] == '\01')
50 ++Name;
51}
52
John McCallf0c11f72011-03-31 08:03:29 +000053// Anchor the vtable to this translation unit.
54CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
55
John McCall6b5a61b2011-02-07 10:33:21 +000056/// Build the given block as a global block.
57static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo,
59 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000060
John McCall6b5a61b2011-02-07 10:33:21 +000061/// Build the helper function to copy a block.
62static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
63 const CGBlockInfo &blockInfo) {
64 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
65}
66
67/// Build the helper function to dipose of a block.
68static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
69 const CGBlockInfo &blockInfo) {
70 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
71}
72
73/// Build the block descriptor constant for a block.
74static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
75 const CGBlockInfo &blockInfo) {
76 ASTContext &C = CGM.getContext();
77
78 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
79 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
80
81 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000082
83 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000084 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000085
86 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000087 // FIXME: What is the right way to say this doesn't fit? We should give
88 // a user diagnostic in that case. Better fix would be to change the
89 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000090 elements.push_back(llvm::ConstantInt::get(ulong,
91 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000092
John McCall6b5a61b2011-02-07 10:33:21 +000093 // Optional copy/dispose helpers.
94 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000095 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000097
98 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000099 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +0000100 }
101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
103 std::string typeAtEncoding =
104 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
105 elements.push_back(llvm::ConstantExpr::getBitCast(
106 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000107
John McCall6b5a61b2011-02-07 10:33:21 +0000108 // GC layout.
109 if (C.getLangOptions().ObjC1)
110 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
111 else
112 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000113
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000114 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000115
John McCall6b5a61b2011-02-07 10:33:21 +0000116 llvm::GlobalVariable *global =
117 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
118 llvm::GlobalValue::InternalLinkage,
119 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000120
John McCall6b5a61b2011-02-07 10:33:21 +0000121 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000122}
123
John McCall6b5a61b2011-02-07 10:33:21 +0000124/*
125 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000126
John McCall6b5a61b2011-02-07 10:33:21 +0000127 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
128 struct Block_literal {
129 /// Initialized to one of:
130 /// extern void *_NSConcreteStackBlock[];
131 /// extern void *_NSConcreteGlobalBlock[];
132 ///
133 /// In theory, we could start one off malloc'ed by setting
134 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
135 /// this isa:
136 /// extern void *_NSConcreteMallocBlock[];
137 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000138
John McCall6b5a61b2011-02-07 10:33:21 +0000139 /// These are the flags (with corresponding bit number) that the
140 /// compiler is actually supposed to know about.
141 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
142 /// descriptor provides copy and dispose helper functions
143 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
144 /// object with a nontrivial destructor or copy constructor
145 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
146 /// as global memory
147 /// 29. BLOCK_USE_STRET - indicates that the block function
148 /// uses stret, which objc_msgSend needs to know about
149 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
150 /// @encoded signature string
151 /// And we're not supposed to manipulate these:
152 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
153 /// to malloc'ed memory
154 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
155 /// to GC-allocated memory
156 /// Additionally, the bottom 16 bits are a reference count which
157 /// should be zero on the stack.
158 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160 /// Reserved; should be zero-initialized.
161 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Function pointer generated from block literal.
164 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Block description metadata generated from block literal.
167 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Captured values follow.
170 _CapturesTypes captures...;
171 };
172 */
David Chisnall5e530af2009-11-17 19:33:30 +0000173
John McCall6b5a61b2011-02-07 10:33:21 +0000174/// The number of fields in a block header.
175const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000176
John McCall6b5a61b2011-02-07 10:33:21 +0000177namespace {
178 /// A chunk of data that we actually have to capture in the block.
179 struct BlockLayoutChunk {
180 CharUnits Alignment;
181 CharUnits Size;
182 const BlockDecl::Capture *Capture; // null for 'this'
183 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000184
John McCall6b5a61b2011-02-07 10:33:21 +0000185 BlockLayoutChunk(CharUnits align, CharUnits size,
186 const BlockDecl::Capture *capture,
187 const llvm::Type *type)
188 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
John McCall6b5a61b2011-02-07 10:33:21 +0000190 /// Tell the block info that this chunk has the given field index.
191 void setIndex(CGBlockInfo &info, unsigned index) {
192 if (!Capture)
193 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000194 else
John McCall6b5a61b2011-02-07 10:33:21 +0000195 info.Captures[Capture->getVariable()]
196 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000197 }
John McCall6b5a61b2011-02-07 10:33:21 +0000198 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000199
John McCall6b5a61b2011-02-07 10:33:21 +0000200 /// Order by descending alignment.
201 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
202 return left.Alignment > right.Alignment;
203 }
204}
205
John McCall461c9c12011-02-08 03:07:00 +0000206/// Determines if the given type is safe for constant capture in C++.
207static bool isSafeForCXXConstantCapture(QualType type) {
208 const RecordType *recordType =
209 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
210
211 // Only records can be unsafe.
212 if (!recordType) return true;
213
214 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
215
216 // Maintain semantics for classes with non-trivial dtors or copy ctors.
217 if (!record->hasTrivialDestructor()) return false;
218 if (!record->hasTrivialCopyConstructor()) return false;
219
220 // Otherwise, we just have to make sure there aren't any mutable
221 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000222 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000223}
224
John McCall6b5a61b2011-02-07 10:33:21 +0000225/// It is illegal to modify a const object after initialization.
226/// Therefore, if a const object has a constant initializer, we don't
227/// actually need to keep storage for it in the block; we'll just
228/// rematerialize it at the start of the block function. This is
229/// acceptable because we make no promises about address stability of
230/// captured variables.
231static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
232 const VarDecl *var) {
233 QualType type = var->getType();
234
235 // We can only do this if the variable is const.
236 if (!type.isConstQualified()) return 0;
237
John McCall461c9c12011-02-08 03:07:00 +0000238 // Furthermore, in C++ we have to worry about mutable fields:
239 // C++ [dcl.type.cv]p4:
240 // Except that any class member declared mutable can be
241 // modified, any attempt to modify a const object during its
242 // lifetime results in undefined behavior.
243 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000244 return 0;
245
246 // If the variable doesn't have any initializer (shouldn't this be
247 // invalid?), it's not clear what we should do. Maybe capture as
248 // zero?
249 const Expr *init = var->getInit();
250 if (!init) return 0;
251
252 return CGM.EmitConstantExpr(init, var->getType());
253}
254
255/// Get the low bit of a nonzero character count. This is the
256/// alignment of the nth byte if the 0th byte is universally aligned.
257static CharUnits getLowBit(CharUnits v) {
258 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
259}
260
261static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
John McCall0774cb82011-05-15 01:53:33 +0000262 llvm::SmallVectorImpl<const llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000263 ASTContext &C = CGM.getContext();
264
265 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
266 CharUnits ptrSize, ptrAlign, intSize, intAlign;
267 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
268 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
269
270 // Are there crazy embedded platforms where this isn't true?
271 assert(intSize <= ptrSize && "layout assumptions horribly violated");
272
273 CharUnits headerSize = ptrSize;
274 if (2 * intSize < ptrAlign) headerSize += ptrSize;
275 else headerSize += 2 * intSize;
276 headerSize += 2 * ptrSize;
277
278 info.BlockAlign = ptrAlign;
279 info.BlockSize = headerSize;
280
281 assert(elementTypes.empty());
282 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
283 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
284 elementTypes.push_back(i8p);
285 elementTypes.push_back(intTy);
286 elementTypes.push_back(intTy);
287 elementTypes.push_back(i8p);
288 elementTypes.push_back(CGM.getBlockDescriptorType());
289
290 assert(elementTypes.size() == BlockHeaderSize);
291}
292
293/// Compute the layout of the given block. Attempts to lay the block
294/// out with minimal space requirements.
295static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
296 ASTContext &C = CGM.getContext();
297 const BlockDecl *block = info.getBlockDecl();
298
John McCall0774cb82011-05-15 01:53:33 +0000299 llvm::SmallVector<const llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000300 initializeForBlockHeader(CGM, info, elementTypes);
301
302 if (!block->hasCaptures()) {
303 info.StructureType =
304 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
305 info.CanBeGlobal = true;
306 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000307 }
Mike Stump00470a12009-03-05 08:32:30 +0000308
John McCall6b5a61b2011-02-07 10:33:21 +0000309 // Collect the layout chunks.
310 llvm::SmallVector<BlockLayoutChunk, 16> layout;
311 layout.reserve(block->capturesCXXThis() +
312 (block->capture_end() - block->capture_begin()));
313
314 CharUnits maxFieldAlign;
315
316 // First, 'this'.
317 if (block->capturesCXXThis()) {
318 const DeclContext *DC = block->getDeclContext();
319 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
320 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000321 QualType thisType;
322 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
323 thisType = C.getPointerType(C.getRecordType(RD));
324 else
325 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000326
327 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
328 std::pair<CharUnits,CharUnits> tinfo
329 = CGM.getContext().getTypeInfoInChars(thisType);
330 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
331
332 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
333 }
334
335 // Next, all the block captures.
336 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
337 ce = block->capture_end(); ci != ce; ++ci) {
338 const VarDecl *variable = ci->getVariable();
339
340 if (ci->isByRef()) {
341 // We have to copy/dispose of the __block reference.
342 info.NeedsCopyDispose = true;
343
John McCall6b5a61b2011-02-07 10:33:21 +0000344 // Just use void* instead of a pointer to the byref type.
345 QualType byRefPtrTy = C.VoidPtrTy;
346
347 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
348 std::pair<CharUnits,CharUnits> tinfo
349 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
350 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
351
352 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
353 &*ci, llvmType));
354 continue;
355 }
356
357 // Otherwise, build a layout chunk with the size and alignment of
358 // the declaration.
359 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
360 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
361 continue;
362 }
363
John McCallf85e1932011-06-15 23:02:42 +0000364 // If we have a lifetime qualifier, honor it for capture purposes.
365 // That includes *not* copying it if it's __unsafe_unretained.
366 if (Qualifiers::ObjCLifetime lifetime
367 = variable->getType().getObjCLifetime()) {
368 switch (lifetime) {
369 case Qualifiers::OCL_None: llvm_unreachable("impossible");
370 case Qualifiers::OCL_ExplicitNone:
371 case Qualifiers::OCL_Autoreleasing:
372 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000373
John McCallf85e1932011-06-15 23:02:42 +0000374 case Qualifiers::OCL_Strong:
375 case Qualifiers::OCL_Weak:
376 info.NeedsCopyDispose = true;
377 }
378
379 // Block pointers require copy/dispose. So do Objective-C pointers.
380 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000381 info.NeedsCopyDispose = true;
382
383 // So do types that require non-trivial copy construction.
384 } else if (ci->hasCopyExpr()) {
385 info.NeedsCopyDispose = true;
386 info.HasCXXObject = true;
387
388 // And so do types with destructors.
389 } else if (CGM.getLangOptions().CPlusPlus) {
390 if (const CXXRecordDecl *record =
391 variable->getType()->getAsCXXRecordDecl()) {
392 if (!record->hasTrivialDestructor()) {
393 info.HasCXXObject = true;
394 info.NeedsCopyDispose = true;
395 }
396 }
397 }
398
399 CharUnits size = C.getTypeSizeInChars(variable->getType());
400 CharUnits align = C.getDeclAlign(variable);
401 maxFieldAlign = std::max(maxFieldAlign, align);
402
403 const llvm::Type *llvmType =
404 CGM.getTypes().ConvertTypeForMem(variable->getType());
405
406 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
407 }
408
409 // If that was everything, we're done here.
410 if (layout.empty()) {
411 info.StructureType =
412 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
413 info.CanBeGlobal = true;
414 return;
415 }
416
417 // Sort the layout by alignment. We have to use a stable sort here
418 // to get reproducible results. There should probably be an
419 // llvm::array_pod_stable_sort.
420 std::stable_sort(layout.begin(), layout.end());
421
422 CharUnits &blockSize = info.BlockSize;
423 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
424
425 // Assuming that the first byte in the header is maximally aligned,
426 // get the alignment of the first byte following the header.
427 CharUnits endAlign = getLowBit(blockSize);
428
429 // If the end of the header isn't satisfactorily aligned for the
430 // maximum thing, look for things that are okay with the header-end
431 // alignment, and keep appending them until we get something that's
432 // aligned right. This algorithm is only guaranteed optimal if
433 // that condition is satisfied at some point; otherwise we can get
434 // things like:
435 // header // next byte has alignment 4
436 // something_with_size_5; // next byte has alignment 1
437 // something_with_alignment_8;
438 // which has 7 bytes of padding, as opposed to the naive solution
439 // which might have less (?).
440 if (endAlign < maxFieldAlign) {
441 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
442 li = layout.begin() + 1, le = layout.end();
443
444 // Look for something that the header end is already
445 // satisfactorily aligned for.
446 for (; li != le && endAlign < li->Alignment; ++li)
447 ;
448
449 // If we found something that's naturally aligned for the end of
450 // the header, keep adding things...
451 if (li != le) {
452 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
453 for (; li != le; ++li) {
454 assert(endAlign >= li->Alignment);
455
456 li->setIndex(info, elementTypes.size());
457 elementTypes.push_back(li->Type);
458 blockSize += li->Size;
459 endAlign = getLowBit(blockSize);
460
461 // ...until we get to the alignment of the maximum field.
462 if (endAlign >= maxFieldAlign)
463 break;
464 }
465
466 // Don't re-append everything we just appended.
467 layout.erase(first, li);
468 }
469 }
470
471 // At this point, we just have to add padding if the end align still
472 // isn't aligned right.
473 if (endAlign < maxFieldAlign) {
474 CharUnits padding = maxFieldAlign - endAlign;
475
John McCall5936e332011-02-15 09:22:45 +0000476 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
477 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000478 blockSize += padding;
479
480 endAlign = getLowBit(blockSize);
481 assert(endAlign >= maxFieldAlign);
482 }
483
484 // Slam everything else on now. This works because they have
485 // strictly decreasing alignment and we expect that size is always a
486 // multiple of alignment.
487 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
488 li = layout.begin(), le = layout.end(); li != le; ++li) {
489 assert(endAlign >= li->Alignment);
490 li->setIndex(info, elementTypes.size());
491 elementTypes.push_back(li->Type);
492 blockSize += li->Size;
493 endAlign = getLowBit(blockSize);
494 }
495
496 info.StructureType =
497 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
498}
499
500/// Emit a block literal expression in the current function.
501llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
502 std::string Name = CurFn->getName();
503 CGBlockInfo blockInfo(blockExpr, Name.c_str());
504
505 // Compute information about the layout, etc., of this block.
506 computeBlockInfo(CGM, blockInfo);
507
508 // Using that metadata, generate the actual block function.
509 llvm::Constant *blockFn
510 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
511 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000512 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000513
514 // If there is nothing to capture, we can emit this as a global block.
515 if (blockInfo.CanBeGlobal)
516 return buildGlobalBlock(CGM, blockInfo, blockFn);
517
518 // Otherwise, we have to emit this as a local block.
519
520 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000521 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000522
523 // Build the block descriptor.
524 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
525
526 const llvm::Type *intTy = ConvertType(getContext().IntTy);
527
528 llvm::AllocaInst *blockAddr =
529 CreateTempAlloca(blockInfo.StructureType, "block");
530 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
531
532 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000533 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000534 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
535 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000536 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000537
538 // Initialize the block literal.
539 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000540 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000541 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
542 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
543 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
544 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
545 "block.invoke"));
546 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
547 "block.descriptor"));
548
549 // Finally, capture all the values into the block.
550 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
551
552 // First, 'this'.
553 if (blockDecl->capturesCXXThis()) {
554 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
555 blockInfo.CXXThisIndex,
556 "block.captured-this.addr");
557 Builder.CreateStore(LoadCXXThis(), addr);
558 }
559
560 // Next, captured variables.
561 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
562 ce = blockDecl->capture_end(); ci != ce; ++ci) {
563 const VarDecl *variable = ci->getVariable();
564 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
565
566 // Ignore constant captures.
567 if (capture.isConstant()) continue;
568
569 QualType type = variable->getType();
570
571 // This will be a [[type]]*, except that a byref entry will just be
572 // an i8**.
573 llvm::Value *blockField =
574 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
575 "block.captured");
576
577 // Compute the address of the thing we're going to move into the
578 // block literal.
579 llvm::Value *src;
580 if (ci->isNested()) {
581 // We need to use the capture from the enclosing block.
582 const CGBlockInfo::Capture &enclosingCapture =
583 BlockInfo->getCapture(variable);
584
585 // This is a [[type]]*, except that a byref entry wil just be an i8**.
586 src = Builder.CreateStructGEP(LoadBlockStruct(),
587 enclosingCapture.getIndex(),
588 "block.capture.addr");
589 } else {
590 // This is a [[type]]*.
591 src = LocalDeclMap[variable];
592 }
593
594 // For byrefs, we just write the pointer to the byref struct into
595 // the block field. There's no need to chase the forwarding
596 // pointer at this point, since we're building something that will
597 // live a shorter life than the stack byref anyway.
598 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000599 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000600 if (ci->isNested())
601 src = Builder.CreateLoad(src, "byref.capture");
602 else
John McCall5936e332011-02-15 09:22:45 +0000603 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000604
John McCall5936e332011-02-15 09:22:45 +0000605 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000606 Builder.CreateStore(src, blockField);
607
608 // If we have a copy constructor, evaluate that into the block field.
609 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
610 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
611
612 // If it's a reference variable, copy the reference into the block field.
613 } else if (type->isReferenceType()) {
614 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
615
616 // Otherwise, fake up a POD copy into the block field.
617 } else {
John McCallf85e1932011-06-15 23:02:42 +0000618 // Fake up a new variable so that EmitScalarInit doesn't think
619 // we're referring to the variable in its own initializer.
620 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
621 /*name*/ 0, type);
622
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 McCalla07398e2011-06-16 04:16:24 +0000635 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
636 LValue::MakeAddr(blockField, type,
637 getContext().getDeclAlign(variable)
638 .getQuantity(),
639 getContext()),
John McCalldf045202011-03-08 09:38:48 +0000640 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000641 }
642
643 // Push a destructor if necessary. The semantics for when this
644 // actually gets run are really obscure.
John McCallf85e1932011-06-15 23:02:42 +0000645 if (!ci->isByRef()) {
646 switch (type.isDestructedType()) {
647 case QualType::DK_none:
648 break;
649 case QualType::DK_cxx_destructor:
650 PushDestructorCleanup(type, blockField);
651 break;
652 case QualType::DK_objc_strong_lifetime:
653 PushARCReleaseCleanup(getARCCleanupKind(), type, blockField, false);
654 break;
655 case QualType::DK_objc_weak_lifetime:
656 // __weak objects on the stack always get EH cleanups.
657 PushARCWeakReleaseCleanup(NormalAndEHCleanup, type, blockField);
658 break;
659 }
660 }
John McCall6b5a61b2011-02-07 10:33:21 +0000661 }
662
663 // Cast to the converted block-pointer type, which happens (somewhat
664 // unfortunately) to be a pointer to function type.
665 llvm::Value *result =
666 Builder.CreateBitCast(blockAddr,
667 ConvertType(blockInfo.getBlockExpr()->getType()));
Fariborz Jahanian5d9b6bf2011-06-29 18:41:17 +0000668 if (getLangOptions().CatchUndefined)
Fariborz Jahanian1077e422011-06-28 23:51:26 +0000669 EHStack.pushCleanup<CallMemsetLocalBlockObject>(NormalCleanup, blockAddr,
670 blockInfo.BlockSize);
John McCall711c52b2011-01-05 12:14:39 +0000671
John McCall6b5a61b2011-02-07 10:33:21 +0000672 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000673}
674
675
John McCalld16c2cf2011-02-08 08:22:06 +0000676const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000677 if (BlockDescriptorType)
678 return BlockDescriptorType;
679
Mike Stumpa5448542009-02-13 15:32:32 +0000680 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000681 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000682
Mike Stumpab695142009-02-13 15:16:56 +0000683 // struct __block_descriptor {
684 // unsigned long reserved;
685 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000686 //
687 // // later, the following will be added
688 //
689 // struct {
690 // void (*copyHelper)();
691 // void (*copyHelper)();
692 // } helpers; // !!! optional
693 //
694 // const char *signature; // the block signature
695 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000696 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000697 BlockDescriptorType =
698 llvm::StructType::get(UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000699
700 getModule().addTypeName("struct.__block_descriptor",
701 BlockDescriptorType);
702
John McCall6b5a61b2011-02-07 10:33:21 +0000703 // Now form a pointer to that.
704 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000705 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000706}
707
John McCalld16c2cf2011-02-08 08:22:06 +0000708const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000709 if (GenericBlockLiteralType)
710 return GenericBlockLiteralType;
711
John McCall6b5a61b2011-02-07 10:33:21 +0000712 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000713
Mike Stump9b8a7972009-02-13 15:25:34 +0000714 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000715 // void *__isa;
716 // int __flags;
717 // int __reserved;
718 // void (*__invoke)(void *);
719 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000720 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000721 GenericBlockLiteralType = llvm::StructType::get(VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000722 IntTy,
723 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000724 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000725 BlockDescPtrTy,
726 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000727
Mike Stump9b8a7972009-02-13 15:25:34 +0000728 getModule().addTypeName("struct.__block_literal_generic",
729 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000730
Mike Stump9b8a7972009-02-13 15:25:34 +0000731 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000732}
733
Mike Stumpbd65cac2009-02-19 01:01:04 +0000734
Anders Carlssona1736c02009-12-24 21:13:40 +0000735RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
736 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000737 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000738 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000739
Anders Carlssonacfde802009-02-12 00:39:25 +0000740 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
741
742 // Get a pointer to the generic block literal.
743 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000744 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000745
746 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000747 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000748 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
749
750 // Get the function pointer from the literal.
751 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000752
John McCall5936e332011-02-15 09:22:45 +0000753 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000754
Anders Carlssonacfde802009-02-12 00:39:25 +0000755 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000756 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000757 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000758
Anders Carlsson782f3972009-04-08 23:13:16 +0000759 QualType FnType = BPT->getPointeeType();
760
Anders Carlssonacfde802009-02-12 00:39:25 +0000761 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000762 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000763 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000764
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000765 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000766 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000767
John McCall64cd2322011-03-09 08:39:33 +0000768 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000769 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000770
Mike Stump1eb44332009-09-09 15:08:12 +0000771 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000772 CGM.getTypes().getFunctionInfo(ResultType, Args,
773 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000775 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000776 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000777 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Owen Anderson96e0fc72009-07-29 22:16:19 +0000779 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000780 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Anders Carlssonacfde802009-02-12 00:39:25 +0000782 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000783 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000784}
Anders Carlssond5cab542009-02-12 17:55:02 +0000785
John McCall6b5a61b2011-02-07 10:33:21 +0000786llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
787 bool isByRef) {
788 assert(BlockInfo && "evaluating block ref without block information?");
789 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000790
John McCall6b5a61b2011-02-07 10:33:21 +0000791 // Handle constant captures.
792 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000793
John McCall6b5a61b2011-02-07 10:33:21 +0000794 llvm::Value *addr =
795 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
796 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000797
John McCall6b5a61b2011-02-07 10:33:21 +0000798 if (isByRef) {
799 // addr should be a void** right now. Load, then cast the result
800 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000801
John McCall6b5a61b2011-02-07 10:33:21 +0000802 addr = Builder.CreateLoad(addr);
803 const llvm::PointerType *byrefPointerType
804 = llvm::PointerType::get(BuildByRefType(variable), 0);
805 addr = Builder.CreateBitCast(addr, byrefPointerType,
806 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000807
John McCall6b5a61b2011-02-07 10:33:21 +0000808 // Follow the forwarding pointer.
809 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
810 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000811
John McCall6b5a61b2011-02-07 10:33:21 +0000812 // Cast back to byref* and GEP over to the actual object.
813 addr = Builder.CreateBitCast(addr, byrefPointerType);
814 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
815 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000816 }
817
John McCall6b5a61b2011-02-07 10:33:21 +0000818 if (variable->getType()->isReferenceType())
819 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000820
John McCall6b5a61b2011-02-07 10:33:21 +0000821 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000822}
823
Mike Stump67a64482009-02-14 22:16:35 +0000824llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000825CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000826 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000827 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000828
John McCall6b5a61b2011-02-07 10:33:21 +0000829 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000830 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000831
John McCall6b5a61b2011-02-07 10:33:21 +0000832 // Using that metadata, generate the actual block function.
833 llvm::Constant *blockFn;
834 {
835 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000836 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
837 blockInfo,
838 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000839 }
John McCall5936e332011-02-15 09:22:45 +0000840 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000841
John McCalld16c2cf2011-02-08 08:22:06 +0000842 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000843}
844
John McCall6b5a61b2011-02-07 10:33:21 +0000845static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
846 const CGBlockInfo &blockInfo,
847 llvm::Constant *blockFn) {
848 assert(blockInfo.CanBeGlobal);
849
850 // Generate the constants for the block literal initializer.
851 llvm::Constant *fields[BlockHeaderSize];
852
853 // isa
854 fields[0] = CGM.getNSConcreteGlobalBlock();
855
856 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000857 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
858 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
859
John McCall5936e332011-02-15 09:22:45 +0000860 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000861
862 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000863 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000864
865 // Function
866 fields[3] = blockFn;
867
868 // Descriptor
869 fields[4] = buildBlockDescriptor(CGM, blockInfo);
870
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000871 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000872
873 llvm::GlobalVariable *literal =
874 new llvm::GlobalVariable(CGM.getModule(),
875 init->getType(),
876 /*constant*/ true,
877 llvm::GlobalVariable::InternalLinkage,
878 init,
879 "__block_literal_global");
880 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
881
882 // Return a constant of the appropriately-casted type.
883 const llvm::Type *requiredType =
884 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
885 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000886}
887
Mike Stump00470a12009-03-05 08:32:30 +0000888llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000889CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
890 const CGBlockInfo &blockInfo,
891 const Decl *outerFnDecl,
892 const DeclMapTy &ldm) {
893 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000894
Devang Patel6d1155b2011-03-07 21:53:18 +0000895 // Check if we should generate debug info for this block function.
896 if (CGM.getModuleDebugInfo())
897 DebugInfo = CGM.getModuleDebugInfo();
898
John McCall6b5a61b2011-02-07 10:33:21 +0000899 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Mike Stump7f28a9c2009-03-13 23:34:28 +0000901 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000902 // to be local to this function as well, in case they're directly
903 // referenced in a block.
904 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
905 const VarDecl *var = dyn_cast<VarDecl>(i->first);
906 if (var && !var->hasLocalStorage())
907 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000908 }
909
John McCall6b5a61b2011-02-07 10:33:21 +0000910 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000911
John McCall6b5a61b2011-02-07 10:33:21 +0000912 // Build the argument list.
913 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000914
John McCall6b5a61b2011-02-07 10:33:21 +0000915 // The first argument is the block pointer. Just take it as a void*
916 // and cast it later.
917 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000918 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000919
John McCall8178df32011-02-22 22:38:33 +0000920 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
921 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000922 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000923
John McCall6b5a61b2011-02-07 10:33:21 +0000924 // Now add the rest of the parameters.
925 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
926 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000927 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000928
John McCall6b5a61b2011-02-07 10:33:21 +0000929 // Create the function declaration.
930 const FunctionProtoType *fnType =
931 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
932 const CGFunctionInfo &fnInfo =
933 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
934 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000935 if (CGM.ReturnTypeUsesSRet(fnInfo))
936 blockInfo.UsesStret = true;
937
John McCall6b5a61b2011-02-07 10:33:21 +0000938 const llvm::FunctionType *fnLLVMType =
939 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000940
John McCall6b5a61b2011-02-07 10:33:21 +0000941 MangleBuffer name;
942 CGM.getBlockMangledName(GD, name, blockDecl);
943 llvm::Function *fn =
944 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
945 name.getString(), &CGM.getModule());
946 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000947
John McCall6b5a61b2011-02-07 10:33:21 +0000948 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000949 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000950 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000951 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000952
John McCall8178df32011-02-22 22:38:33 +0000953 // Okay. Undo some of what StartFunction did.
954
955 // Pull the 'self' reference out of the local decl map.
956 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
957 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000958 BlockPointer = Builder.CreateBitCast(blockAddr,
959 blockInfo.StructureType->getPointerTo(),
960 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000961
John McCallea1471e2010-05-20 01:18:31 +0000962 // If we have a C++ 'this' reference, go ahead and force it into
963 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000964 if (blockDecl->capturesCXXThis()) {
965 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
966 blockInfo.CXXThisIndex,
967 "block.captured-this");
968 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000969 }
970
John McCall6b5a61b2011-02-07 10:33:21 +0000971 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
972 // appease it.
973 if (const ObjCMethodDecl *method
974 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
975 const VarDecl *self = method->getSelfDecl();
976
977 // There might not be a capture for 'self', but if there is...
978 if (blockInfo.Captures.count(self)) {
979 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
980 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
981 capture.getIndex(),
982 "block.captured-self");
983 LocalDeclMap[self] = selfAddr;
984 }
985 }
986
987 // Also force all the constant captures.
988 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
989 ce = blockDecl->capture_end(); ci != ce; ++ci) {
990 const VarDecl *variable = ci->getVariable();
991 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
992 if (!capture.isConstant()) continue;
993
994 unsigned align = getContext().getDeclAlign(variable).getQuantity();
995
996 llvm::AllocaInst *alloca =
997 CreateMemTemp(variable->getType(), "block.captured-const");
998 alloca->setAlignment(align);
999
1000 Builder.CreateStore(capture.getConstant(), alloca, align);
1001
1002 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001003 }
1004
Mike Stumpb289b3f2009-10-01 22:29:41 +00001005 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1006 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1007 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1008 --entry_ptr;
1009
John McCall6b5a61b2011-02-07 10:33:21 +00001010 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001011
Mike Stumpde8c5c72009-10-01 00:27:30 +00001012 // Remember where we were...
1013 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001014
Mike Stumpde8c5c72009-10-01 00:27:30 +00001015 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001016 ++entry_ptr;
1017 Builder.SetInsertPoint(entry, entry_ptr);
1018
John McCall6b5a61b2011-02-07 10:33:21 +00001019 // Emit debug information for all the BlockDeclRefDecls.
1020 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001021 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001022 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1023 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1024 const VarDecl *variable = ci->getVariable();
1025 DI->setLocation(variable->getLocation());
1026
1027 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1028 if (capture.isConstant()) {
1029 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1030 Builder);
1031 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001032 }
John McCall6b5a61b2011-02-07 10:33:21 +00001033
John McCall8178df32011-02-22 22:38:33 +00001034 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001035 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001036 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001037 }
John McCall6b5a61b2011-02-07 10:33:21 +00001038
Mike Stumpde8c5c72009-10-01 00:27:30 +00001039 // And resume where we left off.
1040 if (resume == 0)
1041 Builder.ClearInsertionPoint();
1042 else
1043 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001044
John McCall6b5a61b2011-02-07 10:33:21 +00001045 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001046
John McCall6b5a61b2011-02-07 10:33:21 +00001047 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001048}
Mike Stumpa99038c2009-02-28 09:07:16 +00001049
John McCall6b5a61b2011-02-07 10:33:21 +00001050/*
1051 notes.push_back(HelperInfo());
1052 HelperInfo &note = notes.back();
1053 note.index = capture.getIndex();
1054 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1055 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001056
John McCall6b5a61b2011-02-07 10:33:21 +00001057 if (ci->isByRef()) {
1058 note.flag = BLOCK_FIELD_IS_BYREF;
1059 if (type.isObjCGCWeak())
1060 note.flag |= BLOCK_FIELD_IS_WEAK;
1061 } else if (type->isBlockPointerType()) {
1062 note.flag = BLOCK_FIELD_IS_BLOCK;
1063 } else {
1064 note.flag = BLOCK_FIELD_IS_OBJECT;
1065 }
1066 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001067
Mike Stump00470a12009-03-05 08:32:30 +00001068
Mike Stumpa99038c2009-02-28 09:07:16 +00001069
John McCall6b5a61b2011-02-07 10:33:21 +00001070llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001071CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001072 ASTContext &C = getContext();
1073
1074 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001075 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1076 args.push_back(&dstDecl);
1077 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1078 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Mike Stumpa4f668f2009-03-06 01:33:24 +00001080 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001081 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001082
John McCall6b5a61b2011-02-07 10:33:21 +00001083 // FIXME: it would be nice if these were mergeable with things with
1084 // identical semantics.
1085 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001086
1087 llvm::Function *Fn =
1088 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001089 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001090
1091 IdentifierInfo *II
1092 = &CGM.getContext().Idents.get("__copy_helper_block_");
1093
Devang Patel58dc5ca2011-05-02 20:37:08 +00001094 // Check if we should generate debug info for this block helper function.
1095 if (CGM.getModuleDebugInfo())
1096 DebugInfo = CGM.getModuleDebugInfo();
1097
John McCall6b5a61b2011-02-07 10:33:21 +00001098 FunctionDecl *FD = FunctionDecl::Create(C,
1099 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001100 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001101 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001102 SC_Static,
1103 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001104 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001105 true);
John McCalld26bc762011-03-09 04:27:21 +00001106 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001107
John McCall6b5a61b2011-02-07 10:33:21 +00001108 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001109
John McCalld26bc762011-03-09 04:27:21 +00001110 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001111 src = Builder.CreateLoad(src);
1112 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001113
John McCalld26bc762011-03-09 04:27:21 +00001114 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001115 dst = Builder.CreateLoad(dst);
1116 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001117
John McCall6b5a61b2011-02-07 10:33:21 +00001118 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001119
John McCall6b5a61b2011-02-07 10:33:21 +00001120 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1121 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1122 const VarDecl *variable = ci->getVariable();
1123 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001124
John McCall6b5a61b2011-02-07 10:33:21 +00001125 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1126 if (capture.isConstant()) continue;
1127
1128 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001129 BlockFieldFlags flags;
1130
1131 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001132
1133 if (copyExpr) {
1134 assert(!ci->isByRef());
1135 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001136
John McCall6b5a61b2011-02-07 10:33:21 +00001137 } else if (ci->isByRef()) {
1138 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001139 if (type.isObjCGCWeak())
1140 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001141
John McCallf85e1932011-06-15 23:02:42 +00001142 } else if (type->isObjCRetainableType()) {
1143 flags = BLOCK_FIELD_IS_OBJECT;
1144 if (type->isBlockPointerType())
1145 flags = BLOCK_FIELD_IS_BLOCK;
1146
1147 // Special rules for ARC captures:
1148 if (getLangOptions().ObjCAutoRefCount) {
1149 Qualifiers qs = type.getQualifiers();
1150
1151 // Don't generate special copy logic for a captured object
1152 // unless it's __strong or __weak.
1153 if (!qs.hasStrongOrWeakObjCLifetime())
1154 continue;
1155
1156 // Support __weak direct captures.
1157 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1158 isARCWeakCapture = true;
1159 }
1160 } else {
1161 continue;
1162 }
John McCall6b5a61b2011-02-07 10:33:21 +00001163
1164 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001165 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1166 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001167
1168 // If there's an explicit copy expression, we do that.
1169 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001170 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001171 } else if (isARCWeakCapture) {
1172 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001173 } else {
1174 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001175 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1176 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001177 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001178 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001179 }
1180 }
1181
John McCalld16c2cf2011-02-08 08:22:06 +00001182 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001183
John McCall5936e332011-02-15 09:22:45 +00001184 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001185}
1186
John McCall6b5a61b2011-02-07 10:33:21 +00001187llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001188CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001189 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001190
John McCall6b5a61b2011-02-07 10:33:21 +00001191 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001192 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1193 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Mike Stumpa4f668f2009-03-06 01:33:24 +00001195 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001196 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001197
Mike Stump3899a7f2009-06-05 23:26:36 +00001198 // FIXME: We'd like to put these into a mergable by content, with
1199 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001200 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001201
1202 llvm::Function *Fn =
1203 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001204 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001205
Devang Patel58dc5ca2011-05-02 20:37:08 +00001206 // Check if we should generate debug info for this block destroy function.
1207 if (CGM.getModuleDebugInfo())
1208 DebugInfo = CGM.getModuleDebugInfo();
1209
Mike Stumpa4f668f2009-03-06 01:33:24 +00001210 IdentifierInfo *II
1211 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1212
John McCall6b5a61b2011-02-07 10:33:21 +00001213 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001214 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001215 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001216 SC_Static,
1217 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001218 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001219 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001220
John McCall6b5a61b2011-02-07 10:33:21 +00001221 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001222
John McCalld26bc762011-03-09 04:27:21 +00001223 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001224 src = Builder.CreateLoad(src);
1225 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001226
John McCall6b5a61b2011-02-07 10:33:21 +00001227 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1228
John McCalld16c2cf2011-02-08 08:22:06 +00001229 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001230
1231 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1232 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1233 const VarDecl *variable = ci->getVariable();
1234 QualType type = variable->getType();
1235
1236 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1237 if (capture.isConstant()) continue;
1238
John McCalld16c2cf2011-02-08 08:22:06 +00001239 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001240 const CXXDestructorDecl *dtor = 0;
1241
John McCallf85e1932011-06-15 23:02:42 +00001242 bool isARCWeakCapture = false;
1243
John McCall6b5a61b2011-02-07 10:33:21 +00001244 if (ci->isByRef()) {
1245 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001246 if (type.isObjCGCWeak())
1247 flags |= BLOCK_FIELD_IS_WEAK;
1248 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1249 if (record->hasTrivialDestructor())
1250 continue;
1251 dtor = record->getDestructor();
1252 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001253 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001254 if (type->isBlockPointerType())
1255 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001256
John McCallf85e1932011-06-15 23:02:42 +00001257 // Special rules for ARC captures.
1258 if (getLangOptions().ObjCAutoRefCount) {
1259 Qualifiers qs = type.getQualifiers();
1260
1261 // Don't generate special dispose logic for a captured object
1262 // unless it's __strong or __weak.
1263 if (!qs.hasStrongOrWeakObjCLifetime())
1264 continue;
1265
1266 // Support __weak direct captures.
1267 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1268 isARCWeakCapture = true;
1269 }
1270 } else {
1271 continue;
1272 }
John McCall6b5a61b2011-02-07 10:33:21 +00001273
1274 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001275 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001276
1277 // If there's an explicit copy expression, we do that.
1278 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001279 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001280
John McCallf85e1932011-06-15 23:02:42 +00001281 // If this is a __weak capture, emit the release directly.
1282 } else if (isARCWeakCapture) {
1283 EmitARCDestroyWeak(srcField);
1284
John McCall6b5a61b2011-02-07 10:33:21 +00001285 // Otherwise we call _Block_object_dispose. It wouldn't be too
1286 // hard to just emit this as a cleanup if we wanted to make sure
1287 // that things were done in reverse.
1288 } else {
1289 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001290 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001291 BuildBlockRelease(value, flags);
1292 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001293 }
1294
John McCall6b5a61b2011-02-07 10:33:21 +00001295 cleanups.ForceCleanup();
1296
John McCalld16c2cf2011-02-08 08:22:06 +00001297 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001298
John McCall5936e332011-02-15 09:22:45 +00001299 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001300}
1301
John McCallf0c11f72011-03-31 08:03:29 +00001302namespace {
1303
1304/// Emits the copy/dispose helper functions for a __block object of id type.
1305class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1306 BlockFieldFlags Flags;
1307
1308public:
1309 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1310 : ByrefHelpers(alignment), Flags(flags) {}
1311
John McCall36170192011-03-31 09:19:20 +00001312 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1313 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001314 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1315
1316 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1317 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1318
1319 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1320
1321 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1322 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1323 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1324 }
1325
1326 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1327 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1328 llvm::Value *value = CGF.Builder.CreateLoad(field);
1329
1330 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1331 }
1332
1333 void profileImpl(llvm::FoldingSetNodeID &id) const {
1334 id.AddInteger(Flags.getBitMask());
1335 }
1336};
1337
John McCallf85e1932011-06-15 23:02:42 +00001338/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1339class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1340public:
1341 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1342
1343 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1344 llvm::Value *srcField) {
1345 CGF.EmitARCMoveWeak(destField, srcField);
1346 }
1347
1348 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1349 CGF.EmitARCDestroyWeak(field);
1350 }
1351
1352 void profileImpl(llvm::FoldingSetNodeID &id) const {
1353 // 0 is distinguishable from all pointers and byref flags
1354 id.AddInteger(0);
1355 }
1356};
1357
1358/// Emits the copy/dispose helpers for an ARC __block __strong variable
1359/// that's not of block-pointer type.
1360class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1361public:
1362 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1363
1364 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1365 llvm::Value *srcField) {
1366 // Do a "move" by copying the value and then zeroing out the old
1367 // variable.
1368
1369 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1370 llvm::Value *null =
1371 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1372 CGF.Builder.CreateStore(value, destField);
1373 CGF.Builder.CreateStore(null, srcField);
1374 }
1375
1376 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1377 llvm::Value *value = CGF.Builder.CreateLoad(field);
1378 CGF.EmitARCRelease(value, /*precise*/ false);
1379 }
1380
1381 void profileImpl(llvm::FoldingSetNodeID &id) const {
1382 // 1 is distinguishable from all pointers and byref flags
1383 id.AddInteger(1);
1384 }
1385};
1386
John McCallf0c11f72011-03-31 08:03:29 +00001387/// Emits the copy/dispose helpers for a __block variable with a
1388/// nontrivial copy constructor or destructor.
1389class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1390 QualType VarType;
1391 const Expr *CopyExpr;
1392
1393public:
1394 CXXByrefHelpers(CharUnits alignment, QualType type,
1395 const Expr *copyExpr)
1396 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1397
1398 bool needsCopy() const { return CopyExpr != 0; }
1399 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1400 llvm::Value *srcField) {
1401 if (!CopyExpr) return;
1402 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1403 }
1404
1405 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1406 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1407 CGF.PushDestructorCleanup(VarType, field);
1408 CGF.PopCleanupBlocks(cleanupDepth);
1409 }
1410
1411 void profileImpl(llvm::FoldingSetNodeID &id) const {
1412 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1413 }
1414};
1415} // end anonymous namespace
1416
1417static llvm::Constant *
1418generateByrefCopyHelper(CodeGenFunction &CGF,
1419 const llvm::StructType &byrefType,
1420 CodeGenModule::ByrefHelpers &byrefInfo) {
1421 ASTContext &Context = CGF.getContext();
1422
1423 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001424
John McCalld26bc762011-03-09 04:27:21 +00001425 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001426 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001427 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001428
John McCallf0c11f72011-03-31 08:03:29 +00001429 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001430 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Mike Stump45031c02009-03-06 02:29:21 +00001432 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001433 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001434
John McCallf0c11f72011-03-31 08:03:29 +00001435 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001436 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1437
Mike Stump3899a7f2009-06-05 23:26:36 +00001438 // FIXME: We'd like to put these into a mergable by content, with
1439 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001440 llvm::Function *Fn =
1441 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001442 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001443
1444 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001445 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001446
John McCallf0c11f72011-03-31 08:03:29 +00001447 FunctionDecl *FD = FunctionDecl::Create(Context,
1448 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001449 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001450 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001451 SC_Static,
1452 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001453 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001454
John McCallf0c11f72011-03-31 08:03:29 +00001455 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001456
John McCallf0c11f72011-03-31 08:03:29 +00001457 if (byrefInfo.needsCopy()) {
1458 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001459
John McCallf0c11f72011-03-31 08:03:29 +00001460 // dst->x
1461 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1462 destField = CGF.Builder.CreateLoad(destField);
1463 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1464 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001465
John McCallf0c11f72011-03-31 08:03:29 +00001466 // src->x
1467 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1468 srcField = CGF.Builder.CreateLoad(srcField);
1469 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1470 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1471
1472 byrefInfo.emitCopy(CGF, destField, srcField);
1473 }
1474
1475 CGF.FinishFunction();
1476
1477 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001478}
1479
John McCallf0c11f72011-03-31 08:03:29 +00001480/// Build the copy helper for a __block variable.
1481static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1482 const llvm::StructType &byrefType,
1483 CodeGenModule::ByrefHelpers &info) {
1484 CodeGenFunction CGF(CGM);
1485 return generateByrefCopyHelper(CGF, byrefType, info);
1486}
1487
1488/// Generate code for a __block variable's dispose helper.
1489static llvm::Constant *
1490generateByrefDisposeHelper(CodeGenFunction &CGF,
1491 const llvm::StructType &byrefType,
1492 CodeGenModule::ByrefHelpers &byrefInfo) {
1493 ASTContext &Context = CGF.getContext();
1494 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001495
John McCalld26bc762011-03-09 04:27:21 +00001496 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001497 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001498 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Mike Stump45031c02009-03-06 02:29:21 +00001500 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001501 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001502
John McCallf0c11f72011-03-31 08:03:29 +00001503 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001504 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1505
Mike Stump3899a7f2009-06-05 23:26:36 +00001506 // FIXME: We'd like to put these into a mergable by content, with
1507 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001508 llvm::Function *Fn =
1509 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001510 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001511 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001512
1513 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001514 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001515
John McCallf0c11f72011-03-31 08:03:29 +00001516 FunctionDecl *FD = FunctionDecl::Create(Context,
1517 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001518 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001519 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001520 SC_Static,
1521 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001522 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001523 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001524
John McCallf0c11f72011-03-31 08:03:29 +00001525 if (byrefInfo.needsDispose()) {
1526 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1527 V = CGF.Builder.CreateLoad(V);
1528 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1529 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001530
John McCallf0c11f72011-03-31 08:03:29 +00001531 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001532 }
Mike Stump45031c02009-03-06 02:29:21 +00001533
John McCallf0c11f72011-03-31 08:03:29 +00001534 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001535
John McCallf0c11f72011-03-31 08:03:29 +00001536 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001537}
1538
John McCallf0c11f72011-03-31 08:03:29 +00001539/// Build the dispose helper for a __block variable.
1540static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1541 const llvm::StructType &byrefType,
1542 CodeGenModule::ByrefHelpers &info) {
1543 CodeGenFunction CGF(CGM);
1544 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001545}
1546
John McCallf0c11f72011-03-31 08:03:29 +00001547///
1548template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1549 const llvm::StructType &byrefTy,
1550 T &byrefInfo) {
1551 // Increase the field's alignment to be at least pointer alignment,
1552 // since the layout of the byref struct will guarantee at least that.
1553 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1554 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1555
1556 llvm::FoldingSetNodeID id;
1557 byrefInfo.Profile(id);
1558
1559 void *insertPos;
1560 CodeGenModule::ByrefHelpers *node
1561 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1562 if (node) return static_cast<T*>(node);
1563
1564 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1565 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1566
1567 T *copy = new (CGM.getContext()) T(byrefInfo);
1568 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1569 return copy;
1570}
1571
1572CodeGenModule::ByrefHelpers *
1573CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1574 const AutoVarEmission &emission) {
1575 const VarDecl &var = *emission.Variable;
1576 QualType type = var.getType();
1577
1578 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1579 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1580 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1581
1582 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1583 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1584 }
1585
John McCallf85e1932011-06-15 23:02:42 +00001586 // Otherwise, if we don't have a retainable type, there's nothing to do.
1587 // that the runtime does extra copies.
1588 if (!type->isObjCRetainableType()) return 0;
1589
1590 Qualifiers qs = type.getQualifiers();
1591
1592 // If we have lifetime, that dominates.
1593 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1594 assert(getLangOptions().ObjCAutoRefCount);
1595
1596 switch (lifetime) {
1597 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1598
1599 // These are just bits as far as the runtime is concerned.
1600 case Qualifiers::OCL_ExplicitNone:
1601 case Qualifiers::OCL_Autoreleasing:
1602 return 0;
1603
1604 // Tell the runtime that this is ARC __weak, called by the
1605 // byref routines.
1606 case Qualifiers::OCL_Weak: {
1607 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1608 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1609 }
1610
1611 // ARC __strong __block variables need to be retained.
1612 case Qualifiers::OCL_Strong:
1613 // Block-pointers need to be _Block_copy'ed, so we let the
1614 // runtime be in charge. But we can't use the code below
1615 // because we don't want to set BYREF_CALLER, which will
1616 // just make the runtime ignore us.
1617 if (type->isBlockPointerType()) {
1618 BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
1619 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1620 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1621
1622 // Otherwise, we transfer ownership of the retain from the stack
1623 // to the heap.
1624 } else {
1625 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1626 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1627 }
1628 }
1629 llvm_unreachable("fell out of lifetime switch!");
1630 }
1631
John McCallf0c11f72011-03-31 08:03:29 +00001632 BlockFieldFlags flags;
1633 if (type->isBlockPointerType()) {
1634 flags |= BLOCK_FIELD_IS_BLOCK;
1635 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1636 type->isObjCObjectPointerType()) {
1637 flags |= BLOCK_FIELD_IS_OBJECT;
1638 } else {
1639 return 0;
1640 }
1641
1642 if (type.isObjCGCWeak())
1643 flags |= BLOCK_FIELD_IS_WEAK;
1644
1645 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1646 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001647}
1648
John McCall5af02db2011-03-31 01:59:53 +00001649unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1650 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1651
1652 return ByRefValueInfo.find(VD)->second.second;
1653}
1654
1655llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1656 const VarDecl *V) {
1657 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1658 Loc = Builder.CreateLoad(Loc);
1659 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1660 V->getNameAsString());
1661 return Loc;
1662}
1663
1664/// BuildByRefType - This routine changes a __block variable declared as T x
1665/// into:
1666///
1667/// struct {
1668/// void *__isa;
1669/// void *__forwarding;
1670/// int32_t __flags;
1671/// int32_t __size;
1672/// void *__copy_helper; // only if needed
1673/// void *__destroy_helper; // only if needed
1674/// char padding[X]; // only if needed
1675/// T x;
1676/// } x
1677///
1678const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1679 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1680 if (Info.first)
1681 return Info.first;
1682
1683 QualType Ty = D->getType();
1684
John McCall0774cb82011-05-15 01:53:33 +00001685 llvm::SmallVector<const llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001686
1687 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1688
1689 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001690 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001691
1692 // void *__forwarding;
John McCall0774cb82011-05-15 01:53:33 +00001693 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
John McCall5af02db2011-03-31 01:59:53 +00001694
1695 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001696 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001697
1698 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001699 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001700
1701 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1702 if (HasCopyAndDispose) {
1703 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001704 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001705
1706 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001707 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001708 }
1709
1710 bool Packed = false;
1711 CharUnits Align = getContext().getDeclAlign(D);
1712 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1713 // We have to insert padding.
1714
1715 // The struct above has 2 32-bit integers.
1716 unsigned CurrentOffsetInBytes = 4 * 2;
1717
1718 // And either 2 or 4 pointers.
1719 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1720 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1721
1722 // Align the offset.
1723 unsigned AlignedOffsetInBytes =
1724 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1725
1726 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1727 if (NumPaddingBytes > 0) {
1728 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1729 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001730 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001731 if (NumPaddingBytes > 1)
1732 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1733
John McCall0774cb82011-05-15 01:53:33 +00001734 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001735
1736 // We want a packed struct.
1737 Packed = true;
1738 }
1739 }
1740
1741 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001742 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001743
John McCall0774cb82011-05-15 01:53:33 +00001744 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001745
1746 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1747 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1748 ByRefTypeHolder.get());
1749
1750 Info.first = ByRefTypeHolder.get();
1751
John McCall0774cb82011-05-15 01:53:33 +00001752 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001753
1754 return Info.first;
1755}
1756
1757/// Initialize the structural components of a __block variable, i.e.
1758/// everything but the actual object.
1759void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001760 // Find the address of the local.
1761 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001762
John McCallf0c11f72011-03-31 08:03:29 +00001763 // That's an alloca of the byref structure type.
1764 const llvm::StructType *byrefType = cast<llvm::StructType>(
1765 cast<llvm::PointerType>(addr->getType())->getElementType());
1766
1767 // Build the byref helpers if necessary. This is null if we don't need any.
1768 CodeGenModule::ByrefHelpers *helpers =
1769 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001770
1771 const VarDecl &D = *emission.Variable;
1772 QualType type = D.getType();
1773
John McCallf0c11f72011-03-31 08:03:29 +00001774 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001775
1776 // Initialize the 'isa', which is just 0 or 1.
1777 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001778 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001779 isa = 1;
1780 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1781 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1782
1783 // Store the address of the variable into its own forwarding pointer.
1784 Builder.CreateStore(addr,
1785 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1786
1787 // Blocks ABI:
1788 // c) the flags field is set to either 0 if no helper functions are
1789 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1790 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001791 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001792 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1793 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1794
John McCallf0c11f72011-03-31 08:03:29 +00001795 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1796 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001797 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1798
John McCallf0c11f72011-03-31 08:03:29 +00001799 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001800 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001801 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001802
1803 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001804 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001805 }
1806}
1807
John McCalld16c2cf2011-02-08 08:22:06 +00001808void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001809 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001810 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001811 V = Builder.CreateBitCast(V, Int8PtrTy);
1812 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001813 Builder.CreateCall2(F, V, N);
1814}
John McCall5af02db2011-03-31 01:59:53 +00001815
1816namespace {
1817 struct CallBlockRelease : EHScopeStack::Cleanup {
1818 llvm::Value *Addr;
1819 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1820
1821 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallf85e1932011-06-15 23:02:42 +00001822 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001823 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1824 }
1825 };
1826}
1827
1828/// Enter a cleanup to destroy a __block variable. Note that this
1829/// cleanup should be a no-op if the variable hasn't left the stack
1830/// yet; if a cleanup is required for the variable itself, that needs
1831/// to be done externally.
1832void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1833 // We don't enter this cleanup if we're in pure-GC mode.
1834 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1835 return;
1836
1837 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1838}