blob: ac47034325b7b43f591f5bb264349a55ff66cfbc [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000022#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall6b5a61b2011-02-07 10:33:21 +000028CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
29 : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall64cd2322011-03-09 08:39:33 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockExpr) {
John McCallee504292010-05-21 04:11:14 +000031
32 // Skip asm prefix, if any.
33 if (Name && Name[0] == '\01')
34 ++Name;
35}
36
John McCallf0c11f72011-03-31 08:03:29 +000037// Anchor the vtable to this translation unit.
38CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
39
John McCall6b5a61b2011-02-07 10:33:21 +000040/// Build the given block as a global block.
41static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
42 const CGBlockInfo &blockInfo,
43 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000044
John McCall6b5a61b2011-02-07 10:33:21 +000045/// Build the helper function to copy a block.
46static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo) {
48 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
49}
50
51/// Build the helper function to dipose of a block.
52static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
55}
56
57/// Build the block descriptor constant for a block.
58static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 ASTContext &C = CGM.getContext();
61
62 const llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
64
65 llvm::SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000066
67 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000068 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000069
70 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000071 // FIXME: What is the right way to say this doesn't fit? We should give
72 // a user diagnostic in that case. Better fix would be to change the
73 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000074 elements.push_back(llvm::ConstantInt::get(ulong,
75 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000076
John McCall6b5a61b2011-02-07 10:33:21 +000077 // Optional copy/dispose helpers.
78 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000079 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000080 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000084 }
85
John McCall6b5a61b2011-02-07 10:33:21 +000086 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
87 std::string typeAtEncoding =
88 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
89 elements.push_back(llvm::ConstantExpr::getBitCast(
90 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // GC layout.
93 if (C.getLangOptions().ObjC1)
94 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
95 else
96 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000097
John McCall6b5a61b2011-02-07 10:33:21 +000098 llvm::Constant *init =
99 llvm::ConstantStruct::get(CGM.getLLVMContext(), elements.data(),
100 elements.size(), false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
169 const llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
173 const llvm::Type *type)
174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
218 const VarDecl *var) {
219 QualType type = var->getType();
220
221 // We can only do this if the variable is const.
222 if (!type.isConstQualified()) return 0;
223
John McCall461c9c12011-02-08 03:07:00 +0000224 // Furthermore, in C++ we have to worry about mutable fields:
225 // C++ [dcl.type.cv]p4:
226 // Except that any class member declared mutable can be
227 // modified, any attempt to modify a const object during its
228 // lifetime results in undefined behavior.
229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000230 return 0;
231
232 // If the variable doesn't have any initializer (shouldn't this be
233 // invalid?), it's not clear what we should do. Maybe capture as
234 // zero?
235 const Expr *init = var->getInit();
236 if (!init) return 0;
237
238 return CGM.EmitConstantExpr(init, var->getType());
239}
240
241/// Get the low bit of a nonzero character count. This is the
242/// alignment of the nth byte if the 0th byte is universally aligned.
243static CharUnits getLowBit(CharUnits v) {
244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
245}
246
247static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
John McCall0774cb82011-05-15 01:53:33 +0000248 llvm::SmallVectorImpl<const llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000249 ASTContext &C = CGM.getContext();
250
251 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
252 CharUnits ptrSize, ptrAlign, intSize, intAlign;
253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
255
256 // Are there crazy embedded platforms where this isn't true?
257 assert(intSize <= ptrSize && "layout assumptions horribly violated");
258
259 CharUnits headerSize = ptrSize;
260 if (2 * intSize < ptrAlign) headerSize += ptrSize;
261 else headerSize += 2 * intSize;
262 headerSize += 2 * ptrSize;
263
264 info.BlockAlign = ptrAlign;
265 info.BlockSize = headerSize;
266
267 assert(elementTypes.empty());
268 const llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
269 const llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
270 elementTypes.push_back(i8p);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(i8p);
274 elementTypes.push_back(CGM.getBlockDescriptorType());
275
276 assert(elementTypes.size() == BlockHeaderSize);
277}
278
279/// Compute the layout of the given block. Attempts to lay the block
280/// out with minimal space requirements.
281static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
282 ASTContext &C = CGM.getContext();
283 const BlockDecl *block = info.getBlockDecl();
284
John McCall0774cb82011-05-15 01:53:33 +0000285 llvm::SmallVector<const llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000286 initializeForBlockHeader(CGM, info, elementTypes);
287
288 if (!block->hasCaptures()) {
289 info.StructureType =
290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
291 info.CanBeGlobal = true;
292 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
Mike Stump00470a12009-03-05 08:32:30 +0000294
John McCall6b5a61b2011-02-07 10:33:21 +0000295 // Collect the layout chunks.
296 llvm::SmallVector<BlockLayoutChunk, 16> layout;
297 layout.reserve(block->capturesCXXThis() +
298 (block->capture_end() - block->capture_begin()));
299
300 CharUnits maxFieldAlign;
301
302 // First, 'this'.
303 if (block->capturesCXXThis()) {
304 const DeclContext *DC = block->getDeclContext();
305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
306 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000307 QualType thisType;
308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
309 thisType = C.getPointerType(C.getRecordType(RD));
310 else
311 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000312
313 const llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
314 std::pair<CharUnits,CharUnits> tinfo
315 = CGM.getContext().getTypeInfoInChars(thisType);
316 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
317
318 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
319 }
320
321 // Next, all the block captures.
322 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
323 ce = block->capture_end(); ci != ce; ++ci) {
324 const VarDecl *variable = ci->getVariable();
325
326 if (ci->isByRef()) {
327 // We have to copy/dispose of the __block reference.
328 info.NeedsCopyDispose = true;
329
John McCall6b5a61b2011-02-07 10:33:21 +0000330 // Just use void* instead of a pointer to the byref type.
331 QualType byRefPtrTy = C.VoidPtrTy;
332
333 const llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
334 std::pair<CharUnits,CharUnits> tinfo
335 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
336 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
337
338 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
339 &*ci, llvmType));
340 continue;
341 }
342
343 // Otherwise, build a layout chunk with the size and alignment of
344 // the declaration.
345 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
346 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
347 continue;
348 }
349
John McCallf85e1932011-06-15 23:02:42 +0000350 // If we have a lifetime qualifier, honor it for capture purposes.
351 // That includes *not* copying it if it's __unsafe_unretained.
352 if (Qualifiers::ObjCLifetime lifetime
353 = variable->getType().getObjCLifetime()) {
354 switch (lifetime) {
355 case Qualifiers::OCL_None: llvm_unreachable("impossible");
356 case Qualifiers::OCL_ExplicitNone:
357 case Qualifiers::OCL_Autoreleasing:
358 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000359
John McCallf85e1932011-06-15 23:02:42 +0000360 case Qualifiers::OCL_Strong:
361 case Qualifiers::OCL_Weak:
362 info.NeedsCopyDispose = true;
363 }
364
365 // Block pointers require copy/dispose. So do Objective-C pointers.
366 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000367 info.NeedsCopyDispose = true;
368
369 // So do types that require non-trivial copy construction.
370 } else if (ci->hasCopyExpr()) {
371 info.NeedsCopyDispose = true;
372 info.HasCXXObject = true;
373
374 // And so do types with destructors.
375 } else if (CGM.getLangOptions().CPlusPlus) {
376 if (const CXXRecordDecl *record =
377 variable->getType()->getAsCXXRecordDecl()) {
378 if (!record->hasTrivialDestructor()) {
379 info.HasCXXObject = true;
380 info.NeedsCopyDispose = true;
381 }
382 }
383 }
384
385 CharUnits size = C.getTypeSizeInChars(variable->getType());
386 CharUnits align = C.getDeclAlign(variable);
387 maxFieldAlign = std::max(maxFieldAlign, align);
388
389 const llvm::Type *llvmType =
390 CGM.getTypes().ConvertTypeForMem(variable->getType());
391
392 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
393 }
394
395 // If that was everything, we're done here.
396 if (layout.empty()) {
397 info.StructureType =
398 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
399 info.CanBeGlobal = true;
400 return;
401 }
402
403 // Sort the layout by alignment. We have to use a stable sort here
404 // to get reproducible results. There should probably be an
405 // llvm::array_pod_stable_sort.
406 std::stable_sort(layout.begin(), layout.end());
407
408 CharUnits &blockSize = info.BlockSize;
409 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
410
411 // Assuming that the first byte in the header is maximally aligned,
412 // get the alignment of the first byte following the header.
413 CharUnits endAlign = getLowBit(blockSize);
414
415 // If the end of the header isn't satisfactorily aligned for the
416 // maximum thing, look for things that are okay with the header-end
417 // alignment, and keep appending them until we get something that's
418 // aligned right. This algorithm is only guaranteed optimal if
419 // that condition is satisfied at some point; otherwise we can get
420 // things like:
421 // header // next byte has alignment 4
422 // something_with_size_5; // next byte has alignment 1
423 // something_with_alignment_8;
424 // which has 7 bytes of padding, as opposed to the naive solution
425 // which might have less (?).
426 if (endAlign < maxFieldAlign) {
427 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
428 li = layout.begin() + 1, le = layout.end();
429
430 // Look for something that the header end is already
431 // satisfactorily aligned for.
432 for (; li != le && endAlign < li->Alignment; ++li)
433 ;
434
435 // If we found something that's naturally aligned for the end of
436 // the header, keep adding things...
437 if (li != le) {
438 llvm::SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
439 for (; li != le; ++li) {
440 assert(endAlign >= li->Alignment);
441
442 li->setIndex(info, elementTypes.size());
443 elementTypes.push_back(li->Type);
444 blockSize += li->Size;
445 endAlign = getLowBit(blockSize);
446
447 // ...until we get to the alignment of the maximum field.
448 if (endAlign >= maxFieldAlign)
449 break;
450 }
451
452 // Don't re-append everything we just appended.
453 layout.erase(first, li);
454 }
455 }
456
457 // At this point, we just have to add padding if the end align still
458 // isn't aligned right.
459 if (endAlign < maxFieldAlign) {
460 CharUnits padding = maxFieldAlign - endAlign;
461
John McCall5936e332011-02-15 09:22:45 +0000462 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
463 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000464 blockSize += padding;
465
466 endAlign = getLowBit(blockSize);
467 assert(endAlign >= maxFieldAlign);
468 }
469
470 // Slam everything else on now. This works because they have
471 // strictly decreasing alignment and we expect that size is always a
472 // multiple of alignment.
473 for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
474 li = layout.begin(), le = layout.end(); li != le; ++li) {
475 assert(endAlign >= li->Alignment);
476 li->setIndex(info, elementTypes.size());
477 elementTypes.push_back(li->Type);
478 blockSize += li->Size;
479 endAlign = getLowBit(blockSize);
480 }
481
482 info.StructureType =
483 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
484}
485
486/// Emit a block literal expression in the current function.
487llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
488 std::string Name = CurFn->getName();
489 CGBlockInfo blockInfo(blockExpr, Name.c_str());
490
491 // Compute information about the layout, etc., of this block.
492 computeBlockInfo(CGM, blockInfo);
493
494 // Using that metadata, generate the actual block function.
495 llvm::Constant *blockFn
496 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
497 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000498 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000499
500 // If there is nothing to capture, we can emit this as a global block.
501 if (blockInfo.CanBeGlobal)
502 return buildGlobalBlock(CGM, blockInfo, blockFn);
503
504 // Otherwise, we have to emit this as a local block.
505
506 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000507 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000508
509 // Build the block descriptor.
510 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
511
512 const llvm::Type *intTy = ConvertType(getContext().IntTy);
513
514 llvm::AllocaInst *blockAddr =
515 CreateTempAlloca(blockInfo.StructureType, "block");
516 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
517
518 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000519 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000520 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
521 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000522 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000523
524 // Initialize the block literal.
525 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000526 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000527 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
528 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
529 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
530 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
531 "block.invoke"));
532 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
533 "block.descriptor"));
534
535 // Finally, capture all the values into the block.
536 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
537
538 // First, 'this'.
539 if (blockDecl->capturesCXXThis()) {
540 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
541 blockInfo.CXXThisIndex,
542 "block.captured-this.addr");
543 Builder.CreateStore(LoadCXXThis(), addr);
544 }
545
546 // Next, captured variables.
547 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
548 ce = blockDecl->capture_end(); ci != ce; ++ci) {
549 const VarDecl *variable = ci->getVariable();
550 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
551
552 // Ignore constant captures.
553 if (capture.isConstant()) continue;
554
555 QualType type = variable->getType();
556
557 // This will be a [[type]]*, except that a byref entry will just be
558 // an i8**.
559 llvm::Value *blockField =
560 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
561 "block.captured");
562
563 // Compute the address of the thing we're going to move into the
564 // block literal.
565 llvm::Value *src;
566 if (ci->isNested()) {
567 // We need to use the capture from the enclosing block.
568 const CGBlockInfo::Capture &enclosingCapture =
569 BlockInfo->getCapture(variable);
570
571 // This is a [[type]]*, except that a byref entry wil just be an i8**.
572 src = Builder.CreateStructGEP(LoadBlockStruct(),
573 enclosingCapture.getIndex(),
574 "block.capture.addr");
575 } else {
576 // This is a [[type]]*.
577 src = LocalDeclMap[variable];
578 }
579
580 // For byrefs, we just write the pointer to the byref struct into
581 // the block field. There's no need to chase the forwarding
582 // pointer at this point, since we're building something that will
583 // live a shorter life than the stack byref anyway.
584 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000585 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000586 if (ci->isNested())
587 src = Builder.CreateLoad(src, "byref.capture");
588 else
John McCall5936e332011-02-15 09:22:45 +0000589 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000590
John McCall5936e332011-02-15 09:22:45 +0000591 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000592 Builder.CreateStore(src, blockField);
593
594 // If we have a copy constructor, evaluate that into the block field.
595 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
596 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
597
598 // If it's a reference variable, copy the reference into the block field.
599 } else if (type->isReferenceType()) {
600 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
601
602 // Otherwise, fake up a POD copy into the block field.
603 } else {
John McCallf85e1932011-06-15 23:02:42 +0000604 // Fake up a new variable so that EmitScalarInit doesn't think
605 // we're referring to the variable in its own initializer.
606 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
607 /*name*/ 0, type);
608
John McCallbb699b02011-02-07 18:37:40 +0000609 // We use one of these or the other depending on whether the
610 // reference is nested.
611 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
612 SourceLocation());
613 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
614 VK_LValue, SourceLocation(), /*byref*/ false);
615
616 Expr *declRef =
617 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
618
John McCall6b5a61b2011-02-07 10:33:21 +0000619 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000620 declRef, VK_RValue);
John McCallf85e1932011-06-15 23:02:42 +0000621 EmitExprAsInit(&l2r, &blockFieldPseudoVar, blockField,
John McCalldf045202011-03-08 09:38:48 +0000622 getContext().getDeclAlign(variable),
623 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000624 }
625
626 // Push a destructor if necessary. The semantics for when this
627 // actually gets run are really obscure.
John McCallf85e1932011-06-15 23:02:42 +0000628 if (!ci->isByRef()) {
629 switch (type.isDestructedType()) {
630 case QualType::DK_none:
631 break;
632 case QualType::DK_cxx_destructor:
633 PushDestructorCleanup(type, blockField);
634 break;
635 case QualType::DK_objc_strong_lifetime:
636 PushARCReleaseCleanup(getARCCleanupKind(), type, blockField, false);
637 break;
638 case QualType::DK_objc_weak_lifetime:
639 // __weak objects on the stack always get EH cleanups.
640 PushARCWeakReleaseCleanup(NormalAndEHCleanup, type, blockField);
641 break;
642 }
643 }
John McCall6b5a61b2011-02-07 10:33:21 +0000644 }
645
646 // Cast to the converted block-pointer type, which happens (somewhat
647 // unfortunately) to be a pointer to function type.
648 llvm::Value *result =
649 Builder.CreateBitCast(blockAddr,
650 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000651
John McCall6b5a61b2011-02-07 10:33:21 +0000652 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000653}
654
655
John McCalld16c2cf2011-02-08 08:22:06 +0000656const llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000657 if (BlockDescriptorType)
658 return BlockDescriptorType;
659
Mike Stumpa5448542009-02-13 15:32:32 +0000660 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000661 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000662
Mike Stumpab695142009-02-13 15:16:56 +0000663 // struct __block_descriptor {
664 // unsigned long reserved;
665 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000666 //
667 // // later, the following will be added
668 //
669 // struct {
670 // void (*copyHelper)();
671 // void (*copyHelper)();
672 // } helpers; // !!! optional
673 //
674 // const char *signature; // the block signature
675 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000676 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000677 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
678 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000679 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000680 NULL);
681
682 getModule().addTypeName("struct.__block_descriptor",
683 BlockDescriptorType);
684
John McCall6b5a61b2011-02-07 10:33:21 +0000685 // Now form a pointer to that.
686 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000687 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000688}
689
John McCalld16c2cf2011-02-08 08:22:06 +0000690const llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000691 if (GenericBlockLiteralType)
692 return GenericBlockLiteralType;
693
John McCall6b5a61b2011-02-07 10:33:21 +0000694 const llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000695
Mike Stump9b8a7972009-02-13 15:25:34 +0000696 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000697 // void *__isa;
698 // int __flags;
699 // int __reserved;
700 // void (*__invoke)(void *);
701 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000702 // };
John McCall5936e332011-02-15 09:22:45 +0000703 GenericBlockLiteralType = llvm::StructType::get(getLLVMContext(),
704 VoidPtrTy,
Mike Stump7cbb3602009-02-13 16:01:35 +0000705 IntTy,
706 IntTy,
John McCall5936e332011-02-15 09:22:45 +0000707 VoidPtrTy,
Mike Stump9b8a7972009-02-13 15:25:34 +0000708 BlockDescPtrTy,
709 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000710
Mike Stump9b8a7972009-02-13 15:25:34 +0000711 getModule().addTypeName("struct.__block_literal_generic",
712 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000713
Mike Stump9b8a7972009-02-13 15:25:34 +0000714 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000715}
716
Mike Stumpbd65cac2009-02-19 01:01:04 +0000717
Anders Carlssona1736c02009-12-24 21:13:40 +0000718RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
719 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000720 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000721 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000722
Anders Carlssonacfde802009-02-12 00:39:25 +0000723 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
724
725 // Get a pointer to the generic block literal.
726 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000727 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000728
729 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000730 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000731 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
732
733 // Get the function pointer from the literal.
734 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000735
John McCall5936e332011-02-15 09:22:45 +0000736 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy, "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000737
Anders Carlssonacfde802009-02-12 00:39:25 +0000738 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000739 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000740 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000741
Anders Carlsson782f3972009-04-08 23:13:16 +0000742 QualType FnType = BPT->getPointeeType();
743
Anders Carlssonacfde802009-02-12 00:39:25 +0000744 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000745 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000746 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000747
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000748 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000749 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000750
John McCall64cd2322011-03-09 08:39:33 +0000751 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCall04a67a62010-02-05 21:31:56 +0000752 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000753
Mike Stump1eb44332009-09-09 15:08:12 +0000754 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000755 CGM.getTypes().getFunctionInfo(ResultType, Args,
756 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000758 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000759 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000760 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Owen Anderson96e0fc72009-07-29 22:16:19 +0000762 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000763 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Anders Carlssonacfde802009-02-12 00:39:25 +0000765 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000766 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000767}
Anders Carlssond5cab542009-02-12 17:55:02 +0000768
John McCall6b5a61b2011-02-07 10:33:21 +0000769llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
770 bool isByRef) {
771 assert(BlockInfo && "evaluating block ref without block information?");
772 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000773
John McCall6b5a61b2011-02-07 10:33:21 +0000774 // Handle constant captures.
775 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000776
John McCall6b5a61b2011-02-07 10:33:21 +0000777 llvm::Value *addr =
778 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
779 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000780
John McCall6b5a61b2011-02-07 10:33:21 +0000781 if (isByRef) {
782 // addr should be a void** right now. Load, then cast the result
783 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000784
John McCall6b5a61b2011-02-07 10:33:21 +0000785 addr = Builder.CreateLoad(addr);
786 const llvm::PointerType *byrefPointerType
787 = llvm::PointerType::get(BuildByRefType(variable), 0);
788 addr = Builder.CreateBitCast(addr, byrefPointerType,
789 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000790
John McCall6b5a61b2011-02-07 10:33:21 +0000791 // Follow the forwarding pointer.
792 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
793 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 // Cast back to byref* and GEP over to the actual object.
796 addr = Builder.CreateBitCast(addr, byrefPointerType);
797 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
798 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000799 }
800
John McCall6b5a61b2011-02-07 10:33:21 +0000801 if (variable->getType()->isReferenceType())
802 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000803
John McCall6b5a61b2011-02-07 10:33:21 +0000804 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000805}
806
Mike Stump67a64482009-02-14 22:16:35 +0000807llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000808CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000809 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000810 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000811
John McCall6b5a61b2011-02-07 10:33:21 +0000812 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000813 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000814
John McCall6b5a61b2011-02-07 10:33:21 +0000815 // Using that metadata, generate the actual block function.
816 llvm::Constant *blockFn;
817 {
818 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000819 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
820 blockInfo,
821 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000822 }
John McCall5936e332011-02-15 09:22:45 +0000823 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000824
John McCalld16c2cf2011-02-08 08:22:06 +0000825 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000826}
827
John McCall6b5a61b2011-02-07 10:33:21 +0000828static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
829 const CGBlockInfo &blockInfo,
830 llvm::Constant *blockFn) {
831 assert(blockInfo.CanBeGlobal);
832
833 // Generate the constants for the block literal initializer.
834 llvm::Constant *fields[BlockHeaderSize];
835
836 // isa
837 fields[0] = CGM.getNSConcreteGlobalBlock();
838
839 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000840 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
841 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
842
John McCall5936e332011-02-15 09:22:45 +0000843 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000844
845 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000846 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000847
848 // Function
849 fields[3] = blockFn;
850
851 // Descriptor
852 fields[4] = buildBlockDescriptor(CGM, blockInfo);
853
854 llvm::Constant *init =
855 llvm::ConstantStruct::get(CGM.getLLVMContext(), fields, BlockHeaderSize,
856 /*packed*/ false);
857
858 llvm::GlobalVariable *literal =
859 new llvm::GlobalVariable(CGM.getModule(),
860 init->getType(),
861 /*constant*/ true,
862 llvm::GlobalVariable::InternalLinkage,
863 init,
864 "__block_literal_global");
865 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
866
867 // Return a constant of the appropriately-casted type.
868 const llvm::Type *requiredType =
869 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
870 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000871}
872
Mike Stump00470a12009-03-05 08:32:30 +0000873llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000874CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
875 const CGBlockInfo &blockInfo,
876 const Decl *outerFnDecl,
877 const DeclMapTy &ldm) {
878 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000879
Devang Patel6d1155b2011-03-07 21:53:18 +0000880 // Check if we should generate debug info for this block function.
881 if (CGM.getModuleDebugInfo())
882 DebugInfo = CGM.getModuleDebugInfo();
883
John McCall6b5a61b2011-02-07 10:33:21 +0000884 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Mike Stump7f28a9c2009-03-13 23:34:28 +0000886 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000887 // to be local to this function as well, in case they're directly
888 // referenced in a block.
889 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
890 const VarDecl *var = dyn_cast<VarDecl>(i->first);
891 if (var && !var->hasLocalStorage())
892 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000893 }
894
John McCall6b5a61b2011-02-07 10:33:21 +0000895 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000896
John McCall6b5a61b2011-02-07 10:33:21 +0000897 // Build the argument list.
898 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000899
John McCall6b5a61b2011-02-07 10:33:21 +0000900 // The first argument is the block pointer. Just take it as a void*
901 // and cast it later.
902 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000903 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000904
John McCall8178df32011-02-22 22:38:33 +0000905 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
906 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000907 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000908
John McCall6b5a61b2011-02-07 10:33:21 +0000909 // Now add the rest of the parameters.
910 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
911 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000912 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 // Create the function declaration.
915 const FunctionProtoType *fnType =
916 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
917 const CGFunctionInfo &fnInfo =
918 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
919 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000920 if (CGM.ReturnTypeUsesSRet(fnInfo))
921 blockInfo.UsesStret = true;
922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 const llvm::FunctionType *fnLLVMType =
924 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000925
John McCall6b5a61b2011-02-07 10:33:21 +0000926 MangleBuffer name;
927 CGM.getBlockMangledName(GD, name, blockDecl);
928 llvm::Function *fn =
929 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
930 name.getString(), &CGM.getModule());
931 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000932
John McCall6b5a61b2011-02-07 10:33:21 +0000933 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000934 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000935 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000936 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000937
John McCall8178df32011-02-22 22:38:33 +0000938 // Okay. Undo some of what StartFunction did.
939
940 // Pull the 'self' reference out of the local decl map.
941 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
942 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000943 BlockPointer = Builder.CreateBitCast(blockAddr,
944 blockInfo.StructureType->getPointerTo(),
945 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000946
John McCallea1471e2010-05-20 01:18:31 +0000947 // If we have a C++ 'this' reference, go ahead and force it into
948 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000949 if (blockDecl->capturesCXXThis()) {
950 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
951 blockInfo.CXXThisIndex,
952 "block.captured-this");
953 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000954 }
955
John McCall6b5a61b2011-02-07 10:33:21 +0000956 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
957 // appease it.
958 if (const ObjCMethodDecl *method
959 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
960 const VarDecl *self = method->getSelfDecl();
961
962 // There might not be a capture for 'self', but if there is...
963 if (blockInfo.Captures.count(self)) {
964 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
965 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
966 capture.getIndex(),
967 "block.captured-self");
968 LocalDeclMap[self] = selfAddr;
969 }
970 }
971
972 // Also force all the constant captures.
973 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
974 ce = blockDecl->capture_end(); ci != ce; ++ci) {
975 const VarDecl *variable = ci->getVariable();
976 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
977 if (!capture.isConstant()) continue;
978
979 unsigned align = getContext().getDeclAlign(variable).getQuantity();
980
981 llvm::AllocaInst *alloca =
982 CreateMemTemp(variable->getType(), "block.captured-const");
983 alloca->setAlignment(align);
984
985 Builder.CreateStore(capture.getConstant(), alloca, align);
986
987 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000988 }
989
Mike Stumpb289b3f2009-10-01 22:29:41 +0000990 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
991 llvm::BasicBlock *entry = Builder.GetInsertBlock();
992 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
993 --entry_ptr;
994
John McCall6b5a61b2011-02-07 10:33:21 +0000995 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000996
Mike Stumpde8c5c72009-10-01 00:27:30 +0000997 // Remember where we were...
998 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000999
Mike Stumpde8c5c72009-10-01 00:27:30 +00001000 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001001 ++entry_ptr;
1002 Builder.SetInsertPoint(entry, entry_ptr);
1003
John McCall6b5a61b2011-02-07 10:33:21 +00001004 // Emit debug information for all the BlockDeclRefDecls.
1005 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001006 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001007 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1008 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1009 const VarDecl *variable = ci->getVariable();
1010 DI->setLocation(variable->getLocation());
1011
1012 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1013 if (capture.isConstant()) {
1014 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1015 Builder);
1016 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001017 }
John McCall6b5a61b2011-02-07 10:33:21 +00001018
John McCall8178df32011-02-22 22:38:33 +00001019 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001020 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001021 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001022 }
John McCall6b5a61b2011-02-07 10:33:21 +00001023
Mike Stumpde8c5c72009-10-01 00:27:30 +00001024 // And resume where we left off.
1025 if (resume == 0)
1026 Builder.ClearInsertionPoint();
1027 else
1028 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001029
John McCall6b5a61b2011-02-07 10:33:21 +00001030 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001031
John McCall6b5a61b2011-02-07 10:33:21 +00001032 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001033}
Mike Stumpa99038c2009-02-28 09:07:16 +00001034
John McCall6b5a61b2011-02-07 10:33:21 +00001035/*
1036 notes.push_back(HelperInfo());
1037 HelperInfo &note = notes.back();
1038 note.index = capture.getIndex();
1039 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1040 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001041
John McCall6b5a61b2011-02-07 10:33:21 +00001042 if (ci->isByRef()) {
1043 note.flag = BLOCK_FIELD_IS_BYREF;
1044 if (type.isObjCGCWeak())
1045 note.flag |= BLOCK_FIELD_IS_WEAK;
1046 } else if (type->isBlockPointerType()) {
1047 note.flag = BLOCK_FIELD_IS_BLOCK;
1048 } else {
1049 note.flag = BLOCK_FIELD_IS_OBJECT;
1050 }
1051 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001052
Mike Stump00470a12009-03-05 08:32:30 +00001053
Mike Stumpa99038c2009-02-28 09:07:16 +00001054
John McCall6b5a61b2011-02-07 10:33:21 +00001055llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001056CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001057 ASTContext &C = getContext();
1058
1059 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001060 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1061 args.push_back(&dstDecl);
1062 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1063 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Mike Stumpa4f668f2009-03-06 01:33:24 +00001065 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001066 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001067
John McCall6b5a61b2011-02-07 10:33:21 +00001068 // FIXME: it would be nice if these were mergeable with things with
1069 // identical semantics.
1070 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001071
1072 llvm::Function *Fn =
1073 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001074 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001075
1076 IdentifierInfo *II
1077 = &CGM.getContext().Idents.get("__copy_helper_block_");
1078
Devang Patel58dc5ca2011-05-02 20:37:08 +00001079 // Check if we should generate debug info for this block helper function.
1080 if (CGM.getModuleDebugInfo())
1081 DebugInfo = CGM.getModuleDebugInfo();
1082
John McCall6b5a61b2011-02-07 10:33:21 +00001083 FunctionDecl *FD = FunctionDecl::Create(C,
1084 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001085 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001086 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001087 SC_Static,
1088 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001089 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001090 true);
John McCalld26bc762011-03-09 04:27:21 +00001091 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001092
John McCall6b5a61b2011-02-07 10:33:21 +00001093 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001094
John McCalld26bc762011-03-09 04:27:21 +00001095 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001096 src = Builder.CreateLoad(src);
1097 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001098
John McCalld26bc762011-03-09 04:27:21 +00001099 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001100 dst = Builder.CreateLoad(dst);
1101 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001102
John McCall6b5a61b2011-02-07 10:33:21 +00001103 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001104
John McCall6b5a61b2011-02-07 10:33:21 +00001105 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1106 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1107 const VarDecl *variable = ci->getVariable();
1108 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001109
John McCall6b5a61b2011-02-07 10:33:21 +00001110 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1111 if (capture.isConstant()) continue;
1112
1113 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001114 BlockFieldFlags flags;
1115
1116 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001117
1118 if (copyExpr) {
1119 assert(!ci->isByRef());
1120 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001121
John McCall6b5a61b2011-02-07 10:33:21 +00001122 } else if (ci->isByRef()) {
1123 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001124 if (type.isObjCGCWeak())
1125 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001126
John McCallf85e1932011-06-15 23:02:42 +00001127 } else if (type->isObjCRetainableType()) {
1128 flags = BLOCK_FIELD_IS_OBJECT;
1129 if (type->isBlockPointerType())
1130 flags = BLOCK_FIELD_IS_BLOCK;
1131
1132 // Special rules for ARC captures:
1133 if (getLangOptions().ObjCAutoRefCount) {
1134 Qualifiers qs = type.getQualifiers();
1135
1136 // Don't generate special copy logic for a captured object
1137 // unless it's __strong or __weak.
1138 if (!qs.hasStrongOrWeakObjCLifetime())
1139 continue;
1140
1141 // Support __weak direct captures.
1142 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1143 isARCWeakCapture = true;
1144 }
1145 } else {
1146 continue;
1147 }
John McCall6b5a61b2011-02-07 10:33:21 +00001148
1149 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001150 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1151 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001152
1153 // If there's an explicit copy expression, we do that.
1154 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001155 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001156 } else if (isARCWeakCapture) {
1157 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001158 } else {
1159 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001160 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1161 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001162 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001163 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001164 }
1165 }
1166
John McCalld16c2cf2011-02-08 08:22:06 +00001167 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001168
John McCall5936e332011-02-15 09:22:45 +00001169 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001170}
1171
John McCall6b5a61b2011-02-07 10:33:21 +00001172llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001173CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001174 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001175
John McCall6b5a61b2011-02-07 10:33:21 +00001176 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001177 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1178 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Mike Stumpa4f668f2009-03-06 01:33:24 +00001180 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001181 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001182
Mike Stump3899a7f2009-06-05 23:26:36 +00001183 // FIXME: We'd like to put these into a mergable by content, with
1184 // internal linkage.
John McCall6b5a61b2011-02-07 10:33:21 +00001185 const llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001186
1187 llvm::Function *Fn =
1188 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001189 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001190
Devang Patel58dc5ca2011-05-02 20:37:08 +00001191 // Check if we should generate debug info for this block destroy function.
1192 if (CGM.getModuleDebugInfo())
1193 DebugInfo = CGM.getModuleDebugInfo();
1194
Mike Stumpa4f668f2009-03-06 01:33:24 +00001195 IdentifierInfo *II
1196 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1197
John McCall6b5a61b2011-02-07 10:33:21 +00001198 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001199 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001200 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001201 SC_Static,
1202 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001203 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001204 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001205
John McCall6b5a61b2011-02-07 10:33:21 +00001206 const llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001207
John McCalld26bc762011-03-09 04:27:21 +00001208 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001209 src = Builder.CreateLoad(src);
1210 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001211
John McCall6b5a61b2011-02-07 10:33:21 +00001212 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1213
John McCalld16c2cf2011-02-08 08:22:06 +00001214 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001215
1216 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1217 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1218 const VarDecl *variable = ci->getVariable();
1219 QualType type = variable->getType();
1220
1221 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1222 if (capture.isConstant()) continue;
1223
John McCalld16c2cf2011-02-08 08:22:06 +00001224 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001225 const CXXDestructorDecl *dtor = 0;
1226
John McCallf85e1932011-06-15 23:02:42 +00001227 bool isARCWeakCapture = false;
1228
John McCall6b5a61b2011-02-07 10:33:21 +00001229 if (ci->isByRef()) {
1230 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001231 if (type.isObjCGCWeak())
1232 flags |= BLOCK_FIELD_IS_WEAK;
1233 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1234 if (record->hasTrivialDestructor())
1235 continue;
1236 dtor = record->getDestructor();
1237 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001238 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001239 if (type->isBlockPointerType())
1240 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001241
John McCallf85e1932011-06-15 23:02:42 +00001242 // Special rules for ARC captures.
1243 if (getLangOptions().ObjCAutoRefCount) {
1244 Qualifiers qs = type.getQualifiers();
1245
1246 // Don't generate special dispose logic for a captured object
1247 // unless it's __strong or __weak.
1248 if (!qs.hasStrongOrWeakObjCLifetime())
1249 continue;
1250
1251 // Support __weak direct captures.
1252 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1253 isARCWeakCapture = true;
1254 }
1255 } else {
1256 continue;
1257 }
John McCall6b5a61b2011-02-07 10:33:21 +00001258
1259 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001260 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001261
1262 // If there's an explicit copy expression, we do that.
1263 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001264 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001265
John McCallf85e1932011-06-15 23:02:42 +00001266 // If this is a __weak capture, emit the release directly.
1267 } else if (isARCWeakCapture) {
1268 EmitARCDestroyWeak(srcField);
1269
John McCall6b5a61b2011-02-07 10:33:21 +00001270 // Otherwise we call _Block_object_dispose. It wouldn't be too
1271 // hard to just emit this as a cleanup if we wanted to make sure
1272 // that things were done in reverse.
1273 } else {
1274 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001275 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001276 BuildBlockRelease(value, flags);
1277 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001278 }
1279
John McCall6b5a61b2011-02-07 10:33:21 +00001280 cleanups.ForceCleanup();
1281
John McCalld16c2cf2011-02-08 08:22:06 +00001282 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001283
John McCall5936e332011-02-15 09:22:45 +00001284 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001285}
1286
John McCallf0c11f72011-03-31 08:03:29 +00001287namespace {
1288
1289/// Emits the copy/dispose helper functions for a __block object of id type.
1290class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1291 BlockFieldFlags Flags;
1292
1293public:
1294 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1295 : ByrefHelpers(alignment), Flags(flags) {}
1296
John McCall36170192011-03-31 09:19:20 +00001297 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1298 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001299 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1300
1301 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1302 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1303
1304 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1305
1306 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1307 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1308 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1309 }
1310
1311 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1312 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1313 llvm::Value *value = CGF.Builder.CreateLoad(field);
1314
1315 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1316 }
1317
1318 void profileImpl(llvm::FoldingSetNodeID &id) const {
1319 id.AddInteger(Flags.getBitMask());
1320 }
1321};
1322
John McCallf85e1932011-06-15 23:02:42 +00001323/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1324class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1325public:
1326 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1327
1328 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1329 llvm::Value *srcField) {
1330 CGF.EmitARCMoveWeak(destField, srcField);
1331 }
1332
1333 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1334 CGF.EmitARCDestroyWeak(field);
1335 }
1336
1337 void profileImpl(llvm::FoldingSetNodeID &id) const {
1338 // 0 is distinguishable from all pointers and byref flags
1339 id.AddInteger(0);
1340 }
1341};
1342
1343/// Emits the copy/dispose helpers for an ARC __block __strong variable
1344/// that's not of block-pointer type.
1345class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1346public:
1347 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1348
1349 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1350 llvm::Value *srcField) {
1351 // Do a "move" by copying the value and then zeroing out the old
1352 // variable.
1353
1354 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1355 llvm::Value *null =
1356 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1357 CGF.Builder.CreateStore(value, destField);
1358 CGF.Builder.CreateStore(null, srcField);
1359 }
1360
1361 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1362 llvm::Value *value = CGF.Builder.CreateLoad(field);
1363 CGF.EmitARCRelease(value, /*precise*/ false);
1364 }
1365
1366 void profileImpl(llvm::FoldingSetNodeID &id) const {
1367 // 1 is distinguishable from all pointers and byref flags
1368 id.AddInteger(1);
1369 }
1370};
1371
John McCallf0c11f72011-03-31 08:03:29 +00001372/// Emits the copy/dispose helpers for a __block variable with a
1373/// nontrivial copy constructor or destructor.
1374class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1375 QualType VarType;
1376 const Expr *CopyExpr;
1377
1378public:
1379 CXXByrefHelpers(CharUnits alignment, QualType type,
1380 const Expr *copyExpr)
1381 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1382
1383 bool needsCopy() const { return CopyExpr != 0; }
1384 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1385 llvm::Value *srcField) {
1386 if (!CopyExpr) return;
1387 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1388 }
1389
1390 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1391 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1392 CGF.PushDestructorCleanup(VarType, field);
1393 CGF.PopCleanupBlocks(cleanupDepth);
1394 }
1395
1396 void profileImpl(llvm::FoldingSetNodeID &id) const {
1397 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1398 }
1399};
1400} // end anonymous namespace
1401
1402static llvm::Constant *
1403generateByrefCopyHelper(CodeGenFunction &CGF,
1404 const llvm::StructType &byrefType,
1405 CodeGenModule::ByrefHelpers &byrefInfo) {
1406 ASTContext &Context = CGF.getContext();
1407
1408 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001409
John McCalld26bc762011-03-09 04:27:21 +00001410 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001411 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001412 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001413
John McCallf0c11f72011-03-31 08:03:29 +00001414 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001415 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Mike Stump45031c02009-03-06 02:29:21 +00001417 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001418 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001419
John McCallf0c11f72011-03-31 08:03:29 +00001420 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001421 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1422
Mike Stump3899a7f2009-06-05 23:26:36 +00001423 // FIXME: We'd like to put these into a mergable by content, with
1424 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001425 llvm::Function *Fn =
1426 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001427 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001428
1429 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001430 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001431
John McCallf0c11f72011-03-31 08:03:29 +00001432 FunctionDecl *FD = FunctionDecl::Create(Context,
1433 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001434 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001435 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001436 SC_Static,
1437 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001438 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001439
John McCallf0c11f72011-03-31 08:03:29 +00001440 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001441
John McCallf0c11f72011-03-31 08:03:29 +00001442 if (byrefInfo.needsCopy()) {
1443 const llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001444
John McCallf0c11f72011-03-31 08:03:29 +00001445 // dst->x
1446 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1447 destField = CGF.Builder.CreateLoad(destField);
1448 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1449 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001450
John McCallf0c11f72011-03-31 08:03:29 +00001451 // src->x
1452 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1453 srcField = CGF.Builder.CreateLoad(srcField);
1454 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1455 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1456
1457 byrefInfo.emitCopy(CGF, destField, srcField);
1458 }
1459
1460 CGF.FinishFunction();
1461
1462 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001463}
1464
John McCallf0c11f72011-03-31 08:03:29 +00001465/// Build the copy helper for a __block variable.
1466static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
1467 const llvm::StructType &byrefType,
1468 CodeGenModule::ByrefHelpers &info) {
1469 CodeGenFunction CGF(CGM);
1470 return generateByrefCopyHelper(CGF, byrefType, info);
1471}
1472
1473/// Generate code for a __block variable's dispose helper.
1474static llvm::Constant *
1475generateByrefDisposeHelper(CodeGenFunction &CGF,
1476 const llvm::StructType &byrefType,
1477 CodeGenModule::ByrefHelpers &byrefInfo) {
1478 ASTContext &Context = CGF.getContext();
1479 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001480
John McCalld26bc762011-03-09 04:27:21 +00001481 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001482 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001483 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Mike Stump45031c02009-03-06 02:29:21 +00001485 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001486 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001487
John McCallf0c11f72011-03-31 08:03:29 +00001488 CodeGenTypes &Types = CGF.CGM.getTypes();
Mike Stump45031c02009-03-06 02:29:21 +00001489 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1490
Mike Stump3899a7f2009-06-05 23:26:36 +00001491 // FIXME: We'd like to put these into a mergable by content, with
1492 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001493 llvm::Function *Fn =
1494 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001495 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001496 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001497
1498 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001499 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001500
John McCallf0c11f72011-03-31 08:03:29 +00001501 FunctionDecl *FD = FunctionDecl::Create(Context,
1502 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001503 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001504 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001505 SC_Static,
1506 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001507 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001508 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001509
John McCallf0c11f72011-03-31 08:03:29 +00001510 if (byrefInfo.needsDispose()) {
1511 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1512 V = CGF.Builder.CreateLoad(V);
1513 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1514 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001515
John McCallf0c11f72011-03-31 08:03:29 +00001516 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001517 }
Mike Stump45031c02009-03-06 02:29:21 +00001518
John McCallf0c11f72011-03-31 08:03:29 +00001519 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001520
John McCallf0c11f72011-03-31 08:03:29 +00001521 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001522}
1523
John McCallf0c11f72011-03-31 08:03:29 +00001524/// Build the dispose helper for a __block variable.
1525static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
1526 const llvm::StructType &byrefType,
1527 CodeGenModule::ByrefHelpers &info) {
1528 CodeGenFunction CGF(CGM);
1529 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001530}
1531
John McCallf0c11f72011-03-31 08:03:29 +00001532///
1533template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
1534 const llvm::StructType &byrefTy,
1535 T &byrefInfo) {
1536 // Increase the field's alignment to be at least pointer alignment,
1537 // since the layout of the byref struct will guarantee at least that.
1538 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1539 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1540
1541 llvm::FoldingSetNodeID id;
1542 byrefInfo.Profile(id);
1543
1544 void *insertPos;
1545 CodeGenModule::ByrefHelpers *node
1546 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1547 if (node) return static_cast<T*>(node);
1548
1549 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1550 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1551
1552 T *copy = new (CGM.getContext()) T(byrefInfo);
1553 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1554 return copy;
1555}
1556
1557CodeGenModule::ByrefHelpers *
1558CodeGenFunction::buildByrefHelpers(const llvm::StructType &byrefType,
1559 const AutoVarEmission &emission) {
1560 const VarDecl &var = *emission.Variable;
1561 QualType type = var.getType();
1562
1563 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1564 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1565 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1566
1567 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1568 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1569 }
1570
John McCallf85e1932011-06-15 23:02:42 +00001571 // Otherwise, if we don't have a retainable type, there's nothing to do.
1572 // that the runtime does extra copies.
1573 if (!type->isObjCRetainableType()) return 0;
1574
1575 Qualifiers qs = type.getQualifiers();
1576
1577 // If we have lifetime, that dominates.
1578 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1579 assert(getLangOptions().ObjCAutoRefCount);
1580
1581 switch (lifetime) {
1582 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1583
1584 // These are just bits as far as the runtime is concerned.
1585 case Qualifiers::OCL_ExplicitNone:
1586 case Qualifiers::OCL_Autoreleasing:
1587 return 0;
1588
1589 // Tell the runtime that this is ARC __weak, called by the
1590 // byref routines.
1591 case Qualifiers::OCL_Weak: {
1592 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1593 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1594 }
1595
1596 // ARC __strong __block variables need to be retained.
1597 case Qualifiers::OCL_Strong:
1598 // Block-pointers need to be _Block_copy'ed, so we let the
1599 // runtime be in charge. But we can't use the code below
1600 // because we don't want to set BYREF_CALLER, which will
1601 // just make the runtime ignore us.
1602 if (type->isBlockPointerType()) {
1603 BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
1604 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1605 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1606
1607 // Otherwise, we transfer ownership of the retain from the stack
1608 // to the heap.
1609 } else {
1610 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1611 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1612 }
1613 }
1614 llvm_unreachable("fell out of lifetime switch!");
1615 }
1616
John McCallf0c11f72011-03-31 08:03:29 +00001617 BlockFieldFlags flags;
1618 if (type->isBlockPointerType()) {
1619 flags |= BLOCK_FIELD_IS_BLOCK;
1620 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1621 type->isObjCObjectPointerType()) {
1622 flags |= BLOCK_FIELD_IS_OBJECT;
1623 } else {
1624 return 0;
1625 }
1626
1627 if (type.isObjCGCWeak())
1628 flags |= BLOCK_FIELD_IS_WEAK;
1629
1630 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1631 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001632}
1633
John McCall5af02db2011-03-31 01:59:53 +00001634unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1635 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1636
1637 return ByRefValueInfo.find(VD)->second.second;
1638}
1639
1640llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1641 const VarDecl *V) {
1642 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1643 Loc = Builder.CreateLoad(Loc);
1644 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1645 V->getNameAsString());
1646 return Loc;
1647}
1648
1649/// BuildByRefType - This routine changes a __block variable declared as T x
1650/// into:
1651///
1652/// struct {
1653/// void *__isa;
1654/// void *__forwarding;
1655/// int32_t __flags;
1656/// int32_t __size;
1657/// void *__copy_helper; // only if needed
1658/// void *__destroy_helper; // only if needed
1659/// char padding[X]; // only if needed
1660/// T x;
1661/// } x
1662///
1663const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1664 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
1665 if (Info.first)
1666 return Info.first;
1667
1668 QualType Ty = D->getType();
1669
John McCall0774cb82011-05-15 01:53:33 +00001670 llvm::SmallVector<const llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001671
1672 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
1673
1674 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001675 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001676
1677 // void *__forwarding;
John McCall0774cb82011-05-15 01:53:33 +00001678 types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
John McCall5af02db2011-03-31 01:59:53 +00001679
1680 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001681 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001682
1683 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001684 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001685
1686 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1687 if (HasCopyAndDispose) {
1688 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001689 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001690
1691 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001692 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001693 }
1694
1695 bool Packed = false;
1696 CharUnits Align = getContext().getDeclAlign(D);
1697 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1698 // We have to insert padding.
1699
1700 // The struct above has 2 32-bit integers.
1701 unsigned CurrentOffsetInBytes = 4 * 2;
1702
1703 // And either 2 or 4 pointers.
1704 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1705 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1706
1707 // Align the offset.
1708 unsigned AlignedOffsetInBytes =
1709 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1710
1711 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1712 if (NumPaddingBytes > 0) {
1713 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
1714 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001715 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001716 if (NumPaddingBytes > 1)
1717 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1718
John McCall0774cb82011-05-15 01:53:33 +00001719 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001720
1721 // We want a packed struct.
1722 Packed = true;
1723 }
1724 }
1725
1726 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001727 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001728
John McCall0774cb82011-05-15 01:53:33 +00001729 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001730
1731 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
1732 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
1733 ByRefTypeHolder.get());
1734
1735 Info.first = ByRefTypeHolder.get();
1736
John McCall0774cb82011-05-15 01:53:33 +00001737 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001738
1739 return Info.first;
1740}
1741
1742/// Initialize the structural components of a __block variable, i.e.
1743/// everything but the actual object.
1744void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001745 // Find the address of the local.
1746 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001747
John McCallf0c11f72011-03-31 08:03:29 +00001748 // That's an alloca of the byref structure type.
1749 const llvm::StructType *byrefType = cast<llvm::StructType>(
1750 cast<llvm::PointerType>(addr->getType())->getElementType());
1751
1752 // Build the byref helpers if necessary. This is null if we don't need any.
1753 CodeGenModule::ByrefHelpers *helpers =
1754 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001755
1756 const VarDecl &D = *emission.Variable;
1757 QualType type = D.getType();
1758
John McCallf0c11f72011-03-31 08:03:29 +00001759 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001760
1761 // Initialize the 'isa', which is just 0 or 1.
1762 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001763 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001764 isa = 1;
1765 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1766 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1767
1768 // Store the address of the variable into its own forwarding pointer.
1769 Builder.CreateStore(addr,
1770 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1771
1772 // Blocks ABI:
1773 // c) the flags field is set to either 0 if no helper functions are
1774 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1775 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001776 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001777 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1778 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1779
John McCallf0c11f72011-03-31 08:03:29 +00001780 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1781 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001782 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1783
John McCallf0c11f72011-03-31 08:03:29 +00001784 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001785 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001786 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001787
1788 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001789 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001790 }
1791}
1792
John McCalld16c2cf2011-02-08 08:22:06 +00001793void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001794 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001795 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001796 V = Builder.CreateBitCast(V, Int8PtrTy);
1797 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001798 Builder.CreateCall2(F, V, N);
1799}
John McCall5af02db2011-03-31 01:59:53 +00001800
1801namespace {
1802 struct CallBlockRelease : EHScopeStack::Cleanup {
1803 llvm::Value *Addr;
1804 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1805
1806 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallf85e1932011-06-15 23:02:42 +00001807 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001808 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1809 }
1810 };
1811}
1812
1813/// Enter a cleanup to destroy a __block variable. Note that this
1814/// cleanup should be a no-op if the variable hasn't left the stack
1815/// yet; if a cleanup is required for the variable itself, that needs
1816/// to be done externally.
1817void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1818 // We don't enter this cleanup if we're in pure-GC mode.
1819 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1820 return;
1821
1822 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1823}