blob: 969495376642af2bdb20f5d12b6c7ba91dd26f60 [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
Chris Lattner2acc6e32011-07-18 04:24:23 +000062 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
63 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000064
Chris Lattner5f9e2722011-07-23 10:55:15 +000065 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
Chris Lattnerc5cbb902011-06-20 04:01:35 +000098 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +000099
John McCall6b5a61b2011-02-07 10:33:21 +0000100 llvm::GlobalVariable *global =
101 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
102 llvm::GlobalValue::InternalLinkage,
103 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000104
John McCall6b5a61b2011-02-07 10:33:21 +0000105 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000106}
107
John McCall6b5a61b2011-02-07 10:33:21 +0000108/*
109 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000110
John McCall6b5a61b2011-02-07 10:33:21 +0000111 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
112 struct Block_literal {
113 /// Initialized to one of:
114 /// extern void *_NSConcreteStackBlock[];
115 /// extern void *_NSConcreteGlobalBlock[];
116 ///
117 /// In theory, we could start one off malloc'ed by setting
118 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
119 /// this isa:
120 /// extern void *_NSConcreteMallocBlock[];
121 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000122
John McCall6b5a61b2011-02-07 10:33:21 +0000123 /// These are the flags (with corresponding bit number) that the
124 /// compiler is actually supposed to know about.
125 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
126 /// descriptor provides copy and dispose helper functions
127 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
128 /// object with a nontrivial destructor or copy constructor
129 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
130 /// as global memory
131 /// 29. BLOCK_USE_STRET - indicates that the block function
132 /// uses stret, which objc_msgSend needs to know about
133 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
134 /// @encoded signature string
135 /// And we're not supposed to manipulate these:
136 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
137 /// to malloc'ed memory
138 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
139 /// to GC-allocated memory
140 /// Additionally, the bottom 16 bits are a reference count which
141 /// should be zero on the stack.
142 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000143
John McCall6b5a61b2011-02-07 10:33:21 +0000144 /// Reserved; should be zero-initialized.
145 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000146
John McCall6b5a61b2011-02-07 10:33:21 +0000147 /// Function pointer generated from block literal.
148 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000149
John McCall6b5a61b2011-02-07 10:33:21 +0000150 /// Block description metadata generated from block literal.
151 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000152
John McCall6b5a61b2011-02-07 10:33:21 +0000153 /// Captured values follow.
154 _CapturesTypes captures...;
155 };
156 */
David Chisnall5e530af2009-11-17 19:33:30 +0000157
John McCall6b5a61b2011-02-07 10:33:21 +0000158/// The number of fields in a block header.
159const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000160
John McCall6b5a61b2011-02-07 10:33:21 +0000161namespace {
162 /// A chunk of data that we actually have to capture in the block.
163 struct BlockLayoutChunk {
164 CharUnits Alignment;
165 CharUnits Size;
166 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000167 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 BlockLayoutChunk(CharUnits align, CharUnits size,
170 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000171 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000172 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000173
John McCall6b5a61b2011-02-07 10:33:21 +0000174 /// Tell the block info that this chunk has the given field index.
175 void setIndex(CGBlockInfo &info, unsigned index) {
176 if (!Capture)
177 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000178 else
John McCall6b5a61b2011-02-07 10:33:21 +0000179 info.Captures[Capture->getVariable()]
180 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000181 }
John McCall6b5a61b2011-02-07 10:33:21 +0000182 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000183
John McCall6b5a61b2011-02-07 10:33:21 +0000184 /// Order by descending alignment.
185 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
186 return left.Alignment > right.Alignment;
187 }
188}
189
John McCall461c9c12011-02-08 03:07:00 +0000190/// Determines if the given type is safe for constant capture in C++.
191static bool isSafeForCXXConstantCapture(QualType type) {
192 const RecordType *recordType =
193 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
194
195 // Only records can be unsafe.
196 if (!recordType) return true;
197
198 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
199
200 // Maintain semantics for classes with non-trivial dtors or copy ctors.
201 if (!record->hasTrivialDestructor()) return false;
202 if (!record->hasTrivialCopyConstructor()) return false;
203
204 // Otherwise, we just have to make sure there aren't any mutable
205 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000206 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000207}
208
John McCall6b5a61b2011-02-07 10:33:21 +0000209/// It is illegal to modify a const object after initialization.
210/// Therefore, if a const object has a constant initializer, we don't
211/// actually need to keep storage for it in the block; we'll just
212/// rematerialize it at the start of the block function. This is
213/// acceptable because we make no promises about address stability of
214/// captured variables.
215static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
216 const VarDecl *var) {
217 QualType type = var->getType();
218
219 // We can only do this if the variable is const.
220 if (!type.isConstQualified()) return 0;
221
John McCall461c9c12011-02-08 03:07:00 +0000222 // Furthermore, in C++ we have to worry about mutable fields:
223 // C++ [dcl.type.cv]p4:
224 // Except that any class member declared mutable can be
225 // modified, any attempt to modify a const object during its
226 // lifetime results in undefined behavior.
227 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000228 return 0;
229
230 // If the variable doesn't have any initializer (shouldn't this be
231 // invalid?), it's not clear what we should do. Maybe capture as
232 // zero?
233 const Expr *init = var->getInit();
234 if (!init) return 0;
235
236 return CGM.EmitConstantExpr(init, var->getType());
237}
238
239/// Get the low bit of a nonzero character count. This is the
240/// alignment of the nth byte if the 0th byte is universally aligned.
241static CharUnits getLowBit(CharUnits v) {
242 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
243}
244
245static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000246 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000247 ASTContext &C = CGM.getContext();
248
249 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
250 CharUnits ptrSize, ptrAlign, intSize, intAlign;
251 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
252 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
253
254 // Are there crazy embedded platforms where this isn't true?
255 assert(intSize <= ptrSize && "layout assumptions horribly violated");
256
257 CharUnits headerSize = ptrSize;
258 if (2 * intSize < ptrAlign) headerSize += ptrSize;
259 else headerSize += 2 * intSize;
260 headerSize += 2 * ptrSize;
261
262 info.BlockAlign = ptrAlign;
263 info.BlockSize = headerSize;
264
265 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000266 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
267 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000268 elementTypes.push_back(i8p);
269 elementTypes.push_back(intTy);
270 elementTypes.push_back(intTy);
271 elementTypes.push_back(i8p);
272 elementTypes.push_back(CGM.getBlockDescriptorType());
273
274 assert(elementTypes.size() == BlockHeaderSize);
275}
276
277/// Compute the layout of the given block. Attempts to lay the block
278/// out with minimal space requirements.
279static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
280 ASTContext &C = CGM.getContext();
281 const BlockDecl *block = info.getBlockDecl();
282
Chris Lattner5f9e2722011-07-23 10:55:15 +0000283 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000284 initializeForBlockHeader(CGM, info, elementTypes);
285
286 if (!block->hasCaptures()) {
287 info.StructureType =
288 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
289 info.CanBeGlobal = true;
290 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000291 }
Mike Stump00470a12009-03-05 08:32:30 +0000292
John McCall6b5a61b2011-02-07 10:33:21 +0000293 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000295 layout.reserve(block->capturesCXXThis() +
296 (block->capture_end() - block->capture_begin()));
297
298 CharUnits maxFieldAlign;
299
300 // First, 'this'.
301 if (block->capturesCXXThis()) {
302 const DeclContext *DC = block->getDeclContext();
303 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
304 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000305 QualType thisType;
306 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
307 thisType = C.getPointerType(C.getRecordType(RD));
308 else
309 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000310
Jay Foadef6de3d2011-07-11 09:56:20 +0000311 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000312 std::pair<CharUnits,CharUnits> tinfo
313 = CGM.getContext().getTypeInfoInChars(thisType);
314 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
315
316 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
317 }
318
319 // Next, all the block captures.
320 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
321 ce = block->capture_end(); ci != ce; ++ci) {
322 const VarDecl *variable = ci->getVariable();
323
324 if (ci->isByRef()) {
325 // We have to copy/dispose of the __block reference.
326 info.NeedsCopyDispose = true;
327
John McCall6b5a61b2011-02-07 10:33:21 +0000328 // Just use void* instead of a pointer to the byref type.
329 QualType byRefPtrTy = C.VoidPtrTy;
330
Jay Foadef6de3d2011-07-11 09:56:20 +0000331 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000332 std::pair<CharUnits,CharUnits> tinfo
333 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
334 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
335
336 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
337 &*ci, llvmType));
338 continue;
339 }
340
341 // Otherwise, build a layout chunk with the size and alignment of
342 // the declaration.
343 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
344 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
345 continue;
346 }
347
John McCallf85e1932011-06-15 23:02:42 +0000348 // If we have a lifetime qualifier, honor it for capture purposes.
349 // That includes *not* copying it if it's __unsafe_unretained.
350 if (Qualifiers::ObjCLifetime lifetime
351 = variable->getType().getObjCLifetime()) {
352 switch (lifetime) {
353 case Qualifiers::OCL_None: llvm_unreachable("impossible");
354 case Qualifiers::OCL_ExplicitNone:
355 case Qualifiers::OCL_Autoreleasing:
356 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000357
John McCallf85e1932011-06-15 23:02:42 +0000358 case Qualifiers::OCL_Strong:
359 case Qualifiers::OCL_Weak:
360 info.NeedsCopyDispose = true;
361 }
362
363 // Block pointers require copy/dispose. So do Objective-C pointers.
364 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000365 info.NeedsCopyDispose = true;
366
367 // So do types that require non-trivial copy construction.
368 } else if (ci->hasCopyExpr()) {
369 info.NeedsCopyDispose = true;
370 info.HasCXXObject = true;
371
372 // And so do types with destructors.
373 } else if (CGM.getLangOptions().CPlusPlus) {
374 if (const CXXRecordDecl *record =
375 variable->getType()->getAsCXXRecordDecl()) {
376 if (!record->hasTrivialDestructor()) {
377 info.HasCXXObject = true;
378 info.NeedsCopyDispose = true;
379 }
380 }
381 }
382
383 CharUnits size = C.getTypeSizeInChars(variable->getType());
384 CharUnits align = C.getDeclAlign(variable);
385 maxFieldAlign = std::max(maxFieldAlign, align);
386
Jay Foadef6de3d2011-07-11 09:56:20 +0000387 llvm::Type *llvmType =
John McCall6b5a61b2011-02-07 10:33:21 +0000388 CGM.getTypes().ConvertTypeForMem(variable->getType());
389
390 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
391 }
392
393 // If that was everything, we're done here.
394 if (layout.empty()) {
395 info.StructureType =
396 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
397 info.CanBeGlobal = true;
398 return;
399 }
400
401 // Sort the layout by alignment. We have to use a stable sort here
402 // to get reproducible results. There should probably be an
403 // llvm::array_pod_stable_sort.
404 std::stable_sort(layout.begin(), layout.end());
405
406 CharUnits &blockSize = info.BlockSize;
407 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
408
409 // Assuming that the first byte in the header is maximally aligned,
410 // get the alignment of the first byte following the header.
411 CharUnits endAlign = getLowBit(blockSize);
412
413 // If the end of the header isn't satisfactorily aligned for the
414 // maximum thing, look for things that are okay with the header-end
415 // alignment, and keep appending them until we get something that's
416 // aligned right. This algorithm is only guaranteed optimal if
417 // that condition is satisfied at some point; otherwise we can get
418 // things like:
419 // header // next byte has alignment 4
420 // something_with_size_5; // next byte has alignment 1
421 // something_with_alignment_8;
422 // which has 7 bytes of padding, as opposed to the naive solution
423 // which might have less (?).
424 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000425 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000426 li = layout.begin() + 1, le = layout.end();
427
428 // Look for something that the header end is already
429 // satisfactorily aligned for.
430 for (; li != le && endAlign < li->Alignment; ++li)
431 ;
432
433 // If we found something that's naturally aligned for the end of
434 // the header, keep adding things...
435 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000436 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000437 for (; li != le; ++li) {
438 assert(endAlign >= li->Alignment);
439
440 li->setIndex(info, elementTypes.size());
441 elementTypes.push_back(li->Type);
442 blockSize += li->Size;
443 endAlign = getLowBit(blockSize);
444
445 // ...until we get to the alignment of the maximum field.
446 if (endAlign >= maxFieldAlign)
447 break;
448 }
449
450 // Don't re-append everything we just appended.
451 layout.erase(first, li);
452 }
453 }
454
455 // At this point, we just have to add padding if the end align still
456 // isn't aligned right.
457 if (endAlign < maxFieldAlign) {
458 CharUnits padding = maxFieldAlign - endAlign;
459
John McCall5936e332011-02-15 09:22:45 +0000460 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
461 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000462 blockSize += padding;
463
464 endAlign = getLowBit(blockSize);
465 assert(endAlign >= maxFieldAlign);
466 }
467
468 // Slam everything else on now. This works because they have
469 // strictly decreasing alignment and we expect that size is always a
470 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000471 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000472 li = layout.begin(), le = layout.end(); li != le; ++li) {
473 assert(endAlign >= li->Alignment);
474 li->setIndex(info, elementTypes.size());
475 elementTypes.push_back(li->Type);
476 blockSize += li->Size;
477 endAlign = getLowBit(blockSize);
478 }
479
480 info.StructureType =
481 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
482}
483
484/// Emit a block literal expression in the current function.
485llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
486 std::string Name = CurFn->getName();
487 CGBlockInfo blockInfo(blockExpr, Name.c_str());
488
489 // Compute information about the layout, etc., of this block.
490 computeBlockInfo(CGM, blockInfo);
491
492 // Using that metadata, generate the actual block function.
493 llvm::Constant *blockFn
494 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
495 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000496 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000497
498 // If there is nothing to capture, we can emit this as a global block.
499 if (blockInfo.CanBeGlobal)
500 return buildGlobalBlock(CGM, blockInfo, blockFn);
501
502 // Otherwise, we have to emit this as a local block.
503
504 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000505 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000506
507 // Build the block descriptor.
508 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
509
Chris Lattner2acc6e32011-07-18 04:24:23 +0000510 llvm::Type *intTy = ConvertType(getContext().IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000511
512 llvm::AllocaInst *blockAddr =
513 CreateTempAlloca(blockInfo.StructureType, "block");
514 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
515
516 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000517 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000518 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
519 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000520 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000521
522 // Initialize the block literal.
523 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000524 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000525 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
526 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
527 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
528 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
529 "block.invoke"));
530 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
531 "block.descriptor"));
532
533 // Finally, capture all the values into the block.
534 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
535
536 // First, 'this'.
537 if (blockDecl->capturesCXXThis()) {
538 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
539 blockInfo.CXXThisIndex,
540 "block.captured-this.addr");
541 Builder.CreateStore(LoadCXXThis(), addr);
542 }
543
544 // Next, captured variables.
545 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
546 ce = blockDecl->capture_end(); ci != ce; ++ci) {
547 const VarDecl *variable = ci->getVariable();
548 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
549
550 // Ignore constant captures.
551 if (capture.isConstant()) continue;
552
553 QualType type = variable->getType();
554
555 // This will be a [[type]]*, except that a byref entry will just be
556 // an i8**.
557 llvm::Value *blockField =
558 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
559 "block.captured");
560
561 // Compute the address of the thing we're going to move into the
562 // block literal.
563 llvm::Value *src;
564 if (ci->isNested()) {
565 // We need to use the capture from the enclosing block.
566 const CGBlockInfo::Capture &enclosingCapture =
567 BlockInfo->getCapture(variable);
568
569 // This is a [[type]]*, except that a byref entry wil just be an i8**.
570 src = Builder.CreateStructGEP(LoadBlockStruct(),
571 enclosingCapture.getIndex(),
572 "block.capture.addr");
573 } else {
574 // This is a [[type]]*.
575 src = LocalDeclMap[variable];
576 }
577
578 // For byrefs, we just write the pointer to the byref struct into
579 // the block field. There's no need to chase the forwarding
580 // pointer at this point, since we're building something that will
581 // live a shorter life than the stack byref anyway.
582 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000583 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000584 if (ci->isNested())
585 src = Builder.CreateLoad(src, "byref.capture");
586 else
John McCall5936e332011-02-15 09:22:45 +0000587 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000588
John McCall5936e332011-02-15 09:22:45 +0000589 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000590 Builder.CreateStore(src, blockField);
591
592 // If we have a copy constructor, evaluate that into the block field.
593 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
594 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
595
596 // If it's a reference variable, copy the reference into the block field.
597 } else if (type->isReferenceType()) {
598 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
599
600 // Otherwise, fake up a POD copy into the block field.
601 } else {
John McCallf85e1932011-06-15 23:02:42 +0000602 // Fake up a new variable so that EmitScalarInit doesn't think
603 // we're referring to the variable in its own initializer.
604 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
605 /*name*/ 0, type);
606
John McCallbb699b02011-02-07 18:37:40 +0000607 // We use one of these or the other depending on whether the
608 // reference is nested.
609 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
610 SourceLocation());
611 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
612 VK_LValue, SourceLocation(), /*byref*/ false);
613
614 Expr *declRef =
615 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
616
John McCall6b5a61b2011-02-07 10:33:21 +0000617 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000618 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000619 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Eli Friedman225bf772011-09-30 18:19:16 +0000620 MakeAddrLValue(blockField, type,
621 getContext().getDeclAlign(variable)
622 .getQuantity()),
John McCalldf045202011-03-08 09:38:48 +0000623 /*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()) {
John McCall9928c482011-07-12 16:41:08 +0000629 switch (QualType::DestructionKind dtorKind = type.isDestructedType()) {
John McCallf85e1932011-06-15 23:02:42 +0000630 case QualType::DK_none:
631 break;
John McCall9928c482011-07-12 16:41:08 +0000632
633 // Block captures count as local values and have imprecise semantics.
634 // They also can't be arrays, so need to worry about that.
John McCall5bcd95e2011-07-12 16:53:04 +0000635 case QualType::DK_objc_strong_lifetime: {
636 // This local is a GCC and MSVC compiler workaround.
637 Destroyer *destroyer = &destroyARCStrongImprecise;
John McCall9928c482011-07-12 16:41:08 +0000638 pushDestroy(getCleanupKind(dtorKind), blockField, type,
John McCall5bcd95e2011-07-12 16:53:04 +0000639 *destroyer, /*useEHCleanupForArray*/ false);
John McCallf85e1932011-06-15 23:02:42 +0000640 break;
John McCall5bcd95e2011-07-12 16:53:04 +0000641 }
John McCall9928c482011-07-12 16:41:08 +0000642
John McCallf85e1932011-06-15 23:02:42 +0000643 case QualType::DK_objc_weak_lifetime:
John McCall9928c482011-07-12 16:41:08 +0000644 case QualType::DK_cxx_destructor:
645 pushDestroy(dtorKind, blockField, type);
John McCallf85e1932011-06-15 23:02:42 +0000646 break;
647 }
648 }
John McCall6b5a61b2011-02-07 10:33:21 +0000649 }
650
651 // Cast to the converted block-pointer type, which happens (somewhat
652 // unfortunately) to be a pointer to function type.
653 llvm::Value *result =
654 Builder.CreateBitCast(blockAddr,
655 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000656
John McCall6b5a61b2011-02-07 10:33:21 +0000657 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000658}
659
660
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000661llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000662 if (BlockDescriptorType)
663 return BlockDescriptorType;
664
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000665 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000666 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000667
Mike Stumpab695142009-02-13 15:16:56 +0000668 // struct __block_descriptor {
669 // unsigned long reserved;
670 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000671 //
672 // // later, the following will be added
673 //
674 // struct {
675 // void (*copyHelper)();
676 // void (*copyHelper)();
677 // } helpers; // !!! optional
678 //
679 // const char *signature; // the block signature
680 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000681 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000682 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000683 llvm::StructType::create("struct.__block_descriptor",
684 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000685
John McCall6b5a61b2011-02-07 10:33:21 +0000686 // Now form a pointer to that.
687 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000688 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000689}
690
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000691llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000692 if (GenericBlockLiteralType)
693 return GenericBlockLiteralType;
694
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000695 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000696
Mike Stump9b8a7972009-02-13 15:25:34 +0000697 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000698 // void *__isa;
699 // int __flags;
700 // int __reserved;
701 // void (*__invoke)(void *);
702 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000703 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000704 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000705 llvm::StructType::create("struct.__block_literal_generic",
706 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
707 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000708
Mike Stump9b8a7972009-02-13 15:25:34 +0000709 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000710}
711
Mike Stumpbd65cac2009-02-19 01:01:04 +0000712
Anders Carlssona1736c02009-12-24 21:13:40 +0000713RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
714 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000715 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000716 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000717
Anders Carlssonacfde802009-02-12 00:39:25 +0000718 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
719
720 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000721 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000722 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000723
724 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000725 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000726 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
727
728 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000729 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000730
Benjamin Kramer578faa82011-09-27 21:06:10 +0000731 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000732
Anders Carlssonacfde802009-02-12 00:39:25 +0000733 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000734 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000735 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000736
Anders Carlsson782f3972009-04-08 23:13:16 +0000737 QualType FnType = BPT->getPointeeType();
738
Anders Carlssonacfde802009-02-12 00:39:25 +0000739 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000740 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000741 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000742
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000743 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000744 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000745
John McCall64cd2322011-03-09 08:39:33 +0000746 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
Eli Friedmanc55db3b2011-08-09 17:38:12 +0000747 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000749 // Cast the function pointer to the right type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000750 llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000751 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattner2acc6e32011-07-18 04:24:23 +0000753 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000754 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Anders Carlssonacfde802009-02-12 00:39:25 +0000756 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000757 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000758}
Anders Carlssond5cab542009-02-12 17:55:02 +0000759
John McCall6b5a61b2011-02-07 10:33:21 +0000760llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
761 bool isByRef) {
762 assert(BlockInfo && "evaluating block ref without block information?");
763 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000764
John McCall6b5a61b2011-02-07 10:33:21 +0000765 // Handle constant captures.
766 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000767
John McCall6b5a61b2011-02-07 10:33:21 +0000768 llvm::Value *addr =
769 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
770 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000771
John McCall6b5a61b2011-02-07 10:33:21 +0000772 if (isByRef) {
773 // addr should be a void** right now. Load, then cast the result
774 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000775
John McCall6b5a61b2011-02-07 10:33:21 +0000776 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000777 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000778 = llvm::PointerType::get(BuildByRefType(variable), 0);
779 addr = Builder.CreateBitCast(addr, byrefPointerType,
780 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000781
John McCall6b5a61b2011-02-07 10:33:21 +0000782 // Follow the forwarding pointer.
783 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
784 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000785
John McCall6b5a61b2011-02-07 10:33:21 +0000786 // Cast back to byref* and GEP over to the actual object.
787 addr = Builder.CreateBitCast(addr, byrefPointerType);
788 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
789 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000790 }
791
John McCall6b5a61b2011-02-07 10:33:21 +0000792 if (variable->getType()->isReferenceType())
793 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000794
John McCall6b5a61b2011-02-07 10:33:21 +0000795 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000796}
797
Mike Stump67a64482009-02-14 22:16:35 +0000798llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000799CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000800 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000801 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000802
John McCall6b5a61b2011-02-07 10:33:21 +0000803 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000804 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000805
John McCall6b5a61b2011-02-07 10:33:21 +0000806 // Using that metadata, generate the actual block function.
807 llvm::Constant *blockFn;
808 {
809 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000810 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
811 blockInfo,
812 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000813 }
John McCall5936e332011-02-15 09:22:45 +0000814 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000815
John McCalld16c2cf2011-02-08 08:22:06 +0000816 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000817}
818
John McCall6b5a61b2011-02-07 10:33:21 +0000819static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
820 const CGBlockInfo &blockInfo,
821 llvm::Constant *blockFn) {
822 assert(blockInfo.CanBeGlobal);
823
824 // Generate the constants for the block literal initializer.
825 llvm::Constant *fields[BlockHeaderSize];
826
827 // isa
828 fields[0] = CGM.getNSConcreteGlobalBlock();
829
830 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000831 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
832 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
833
John McCall5936e332011-02-15 09:22:45 +0000834 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000835
836 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000837 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000838
839 // Function
840 fields[3] = blockFn;
841
842 // Descriptor
843 fields[4] = buildBlockDescriptor(CGM, blockInfo);
844
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000845 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000846
847 llvm::GlobalVariable *literal =
848 new llvm::GlobalVariable(CGM.getModule(),
849 init->getType(),
850 /*constant*/ true,
851 llvm::GlobalVariable::InternalLinkage,
852 init,
853 "__block_literal_global");
854 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
855
856 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000857 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000858 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
859 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000860}
861
Mike Stump00470a12009-03-05 08:32:30 +0000862llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000863CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
864 const CGBlockInfo &blockInfo,
865 const Decl *outerFnDecl,
866 const DeclMapTy &ldm) {
867 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000868
Devang Patel6d1155b2011-03-07 21:53:18 +0000869 // Check if we should generate debug info for this block function.
870 if (CGM.getModuleDebugInfo())
871 DebugInfo = CGM.getModuleDebugInfo();
872
John McCall6b5a61b2011-02-07 10:33:21 +0000873 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Mike Stump7f28a9c2009-03-13 23:34:28 +0000875 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000876 // to be local to this function as well, in case they're directly
877 // referenced in a block.
878 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
879 const VarDecl *var = dyn_cast<VarDecl>(i->first);
880 if (var && !var->hasLocalStorage())
881 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000882 }
883
John McCall6b5a61b2011-02-07 10:33:21 +0000884 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000885
John McCall6b5a61b2011-02-07 10:33:21 +0000886 // Build the argument list.
887 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000888
John McCall6b5a61b2011-02-07 10:33:21 +0000889 // The first argument is the block pointer. Just take it as a void*
890 // and cast it later.
891 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000892 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000893
John McCall8178df32011-02-22 22:38:33 +0000894 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
895 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000896 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000897
John McCall6b5a61b2011-02-07 10:33:21 +0000898 // Now add the rest of the parameters.
899 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
900 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000901 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000902
John McCall6b5a61b2011-02-07 10:33:21 +0000903 // Create the function declaration.
904 const FunctionProtoType *fnType =
905 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
906 const CGFunctionInfo &fnInfo =
907 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
908 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000909 if (CGM.ReturnTypeUsesSRet(fnInfo))
910 blockInfo.UsesStret = true;
911
Chris Lattner2acc6e32011-07-18 04:24:23 +0000912 llvm::FunctionType *fnLLVMType =
John McCall6b5a61b2011-02-07 10:33:21 +0000913 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000914
John McCall6b5a61b2011-02-07 10:33:21 +0000915 MangleBuffer name;
916 CGM.getBlockMangledName(GD, name, blockDecl);
917 llvm::Function *fn =
918 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
919 name.getString(), &CGM.getModule());
920 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000921
John McCall6b5a61b2011-02-07 10:33:21 +0000922 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000923 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000924 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000925 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000926
John McCall8178df32011-02-22 22:38:33 +0000927 // Okay. Undo some of what StartFunction did.
928
929 // Pull the 'self' reference out of the local decl map.
930 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
931 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000932 BlockPointer = Builder.CreateBitCast(blockAddr,
933 blockInfo.StructureType->getPointerTo(),
934 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000935
John McCallea1471e2010-05-20 01:18:31 +0000936 // If we have a C++ 'this' reference, go ahead and force it into
937 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000938 if (blockDecl->capturesCXXThis()) {
939 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
940 blockInfo.CXXThisIndex,
941 "block.captured-this");
942 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000943 }
944
John McCall6b5a61b2011-02-07 10:33:21 +0000945 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
946 // appease it.
947 if (const ObjCMethodDecl *method
948 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
949 const VarDecl *self = method->getSelfDecl();
950
951 // There might not be a capture for 'self', but if there is...
952 if (blockInfo.Captures.count(self)) {
953 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
954 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
955 capture.getIndex(),
956 "block.captured-self");
957 LocalDeclMap[self] = selfAddr;
958 }
959 }
960
961 // Also force all the constant captures.
962 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
963 ce = blockDecl->capture_end(); ci != ce; ++ci) {
964 const VarDecl *variable = ci->getVariable();
965 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
966 if (!capture.isConstant()) continue;
967
968 unsigned align = getContext().getDeclAlign(variable).getQuantity();
969
970 llvm::AllocaInst *alloca =
971 CreateMemTemp(variable->getType(), "block.captured-const");
972 alloca->setAlignment(align);
973
974 Builder.CreateStore(capture.getConstant(), alloca, align);
975
976 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000977 }
978
Mike Stumpb289b3f2009-10-01 22:29:41 +0000979 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
980 llvm::BasicBlock *entry = Builder.GetInsertBlock();
981 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
982 --entry_ptr;
983
John McCall6b5a61b2011-02-07 10:33:21 +0000984 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000985
Mike Stumpde8c5c72009-10-01 00:27:30 +0000986 // Remember where we were...
987 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000988
Mike Stumpde8c5c72009-10-01 00:27:30 +0000989 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000990 ++entry_ptr;
991 Builder.SetInsertPoint(entry, entry_ptr);
992
John McCall6b5a61b2011-02-07 10:33:21 +0000993 // Emit debug information for all the BlockDeclRefDecls.
994 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +0000995 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000996 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
997 ce = blockDecl->capture_end(); ci != ce; ++ci) {
998 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +0000999 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001000
1001 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1002 if (capture.isConstant()) {
1003 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1004 Builder);
1005 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001006 }
John McCall6b5a61b2011-02-07 10:33:21 +00001007
John McCall8178df32011-02-22 22:38:33 +00001008 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001009 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001010 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001011 }
John McCall6b5a61b2011-02-07 10:33:21 +00001012
Mike Stumpde8c5c72009-10-01 00:27:30 +00001013 // And resume where we left off.
1014 if (resume == 0)
1015 Builder.ClearInsertionPoint();
1016 else
1017 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001018
John McCall6b5a61b2011-02-07 10:33:21 +00001019 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001020
John McCall6b5a61b2011-02-07 10:33:21 +00001021 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001022}
Mike Stumpa99038c2009-02-28 09:07:16 +00001023
John McCall6b5a61b2011-02-07 10:33:21 +00001024/*
1025 notes.push_back(HelperInfo());
1026 HelperInfo &note = notes.back();
1027 note.index = capture.getIndex();
1028 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1029 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001030
John McCall6b5a61b2011-02-07 10:33:21 +00001031 if (ci->isByRef()) {
1032 note.flag = BLOCK_FIELD_IS_BYREF;
1033 if (type.isObjCGCWeak())
1034 note.flag |= BLOCK_FIELD_IS_WEAK;
1035 } else if (type->isBlockPointerType()) {
1036 note.flag = BLOCK_FIELD_IS_BLOCK;
1037 } else {
1038 note.flag = BLOCK_FIELD_IS_OBJECT;
1039 }
1040 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001041
Mike Stump00470a12009-03-05 08:32:30 +00001042
Mike Stumpa99038c2009-02-28 09:07:16 +00001043
John McCall6b5a61b2011-02-07 10:33:21 +00001044llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001045CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001046 ASTContext &C = getContext();
1047
1048 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001049 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1050 args.push_back(&dstDecl);
1051 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1052 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Mike Stumpa4f668f2009-03-06 01:33:24 +00001054 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001055 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001056
John McCall6b5a61b2011-02-07 10:33:21 +00001057 // FIXME: it would be nice if these were mergeable with things with
1058 // identical semantics.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001059 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001060
1061 llvm::Function *Fn =
1062 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001063 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001064
1065 IdentifierInfo *II
1066 = &CGM.getContext().Idents.get("__copy_helper_block_");
1067
Devang Patel58dc5ca2011-05-02 20:37:08 +00001068 // Check if we should generate debug info for this block helper function.
1069 if (CGM.getModuleDebugInfo())
1070 DebugInfo = CGM.getModuleDebugInfo();
1071
John McCall6b5a61b2011-02-07 10:33:21 +00001072 FunctionDecl *FD = FunctionDecl::Create(C,
1073 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001074 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001075 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001076 SC_Static,
1077 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001078 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001079 true);
John McCalld26bc762011-03-09 04:27:21 +00001080 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001081
Chris Lattner2acc6e32011-07-18 04:24:23 +00001082 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001083
John McCalld26bc762011-03-09 04:27:21 +00001084 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001085 src = Builder.CreateLoad(src);
1086 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001087
John McCalld26bc762011-03-09 04:27:21 +00001088 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001089 dst = Builder.CreateLoad(dst);
1090 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001091
John McCall6b5a61b2011-02-07 10:33:21 +00001092 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001093
John McCall6b5a61b2011-02-07 10:33:21 +00001094 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1095 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1096 const VarDecl *variable = ci->getVariable();
1097 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001098
John McCall6b5a61b2011-02-07 10:33:21 +00001099 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1100 if (capture.isConstant()) continue;
1101
1102 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001103 BlockFieldFlags flags;
1104
1105 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001106
1107 if (copyExpr) {
1108 assert(!ci->isByRef());
1109 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001110
John McCall6b5a61b2011-02-07 10:33:21 +00001111 } else if (ci->isByRef()) {
1112 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001113 if (type.isObjCGCWeak())
1114 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001115
John McCallf85e1932011-06-15 23:02:42 +00001116 } else if (type->isObjCRetainableType()) {
1117 flags = BLOCK_FIELD_IS_OBJECT;
1118 if (type->isBlockPointerType())
1119 flags = BLOCK_FIELD_IS_BLOCK;
1120
1121 // Special rules for ARC captures:
1122 if (getLangOptions().ObjCAutoRefCount) {
1123 Qualifiers qs = type.getQualifiers();
1124
1125 // Don't generate special copy logic for a captured object
1126 // unless it's __strong or __weak.
1127 if (!qs.hasStrongOrWeakObjCLifetime())
1128 continue;
1129
1130 // Support __weak direct captures.
1131 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1132 isARCWeakCapture = true;
1133 }
1134 } else {
1135 continue;
1136 }
John McCall6b5a61b2011-02-07 10:33:21 +00001137
1138 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001139 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1140 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001141
1142 // If there's an explicit copy expression, we do that.
1143 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001144 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001145 } else if (isARCWeakCapture) {
1146 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001147 } else {
1148 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001149 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1150 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001151 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001152 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001153 }
1154 }
1155
John McCalld16c2cf2011-02-08 08:22:06 +00001156 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001157
John McCall5936e332011-02-15 09:22:45 +00001158 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001159}
1160
John McCall6b5a61b2011-02-07 10:33:21 +00001161llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001162CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001163 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001164
John McCall6b5a61b2011-02-07 10:33:21 +00001165 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001166 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1167 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Mike Stumpa4f668f2009-03-06 01:33:24 +00001169 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001170 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001171
Mike Stump3899a7f2009-06-05 23:26:36 +00001172 // FIXME: We'd like to put these into a mergable by content, with
1173 // internal linkage.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001174 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001175
1176 llvm::Function *Fn =
1177 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001178 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001179
Devang Patel58dc5ca2011-05-02 20:37:08 +00001180 // Check if we should generate debug info for this block destroy function.
1181 if (CGM.getModuleDebugInfo())
1182 DebugInfo = CGM.getModuleDebugInfo();
1183
Mike Stumpa4f668f2009-03-06 01:33:24 +00001184 IdentifierInfo *II
1185 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1186
John McCall6b5a61b2011-02-07 10:33:21 +00001187 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001188 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001189 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001190 SC_Static,
1191 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001192 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001193 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001194
Chris Lattner2acc6e32011-07-18 04:24:23 +00001195 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001196
John McCalld26bc762011-03-09 04:27:21 +00001197 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001198 src = Builder.CreateLoad(src);
1199 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001200
John McCall6b5a61b2011-02-07 10:33:21 +00001201 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1202
John McCalld16c2cf2011-02-08 08:22:06 +00001203 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001204
1205 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1206 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1207 const VarDecl *variable = ci->getVariable();
1208 QualType type = variable->getType();
1209
1210 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1211 if (capture.isConstant()) continue;
1212
John McCalld16c2cf2011-02-08 08:22:06 +00001213 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001214 const CXXDestructorDecl *dtor = 0;
1215
John McCallf85e1932011-06-15 23:02:42 +00001216 bool isARCWeakCapture = false;
1217
John McCall6b5a61b2011-02-07 10:33:21 +00001218 if (ci->isByRef()) {
1219 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001220 if (type.isObjCGCWeak())
1221 flags |= BLOCK_FIELD_IS_WEAK;
1222 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1223 if (record->hasTrivialDestructor())
1224 continue;
1225 dtor = record->getDestructor();
1226 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001227 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001228 if (type->isBlockPointerType())
1229 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001230
John McCallf85e1932011-06-15 23:02:42 +00001231 // Special rules for ARC captures.
1232 if (getLangOptions().ObjCAutoRefCount) {
1233 Qualifiers qs = type.getQualifiers();
1234
1235 // Don't generate special dispose logic for a captured object
1236 // unless it's __strong or __weak.
1237 if (!qs.hasStrongOrWeakObjCLifetime())
1238 continue;
1239
1240 // Support __weak direct captures.
1241 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1242 isARCWeakCapture = true;
1243 }
1244 } else {
1245 continue;
1246 }
John McCall6b5a61b2011-02-07 10:33:21 +00001247
1248 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001249 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001250
1251 // If there's an explicit copy expression, we do that.
1252 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001253 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001254
John McCallf85e1932011-06-15 23:02:42 +00001255 // If this is a __weak capture, emit the release directly.
1256 } else if (isARCWeakCapture) {
1257 EmitARCDestroyWeak(srcField);
1258
John McCall6b5a61b2011-02-07 10:33:21 +00001259 // Otherwise we call _Block_object_dispose. It wouldn't be too
1260 // hard to just emit this as a cleanup if we wanted to make sure
1261 // that things were done in reverse.
1262 } else {
1263 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001264 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001265 BuildBlockRelease(value, flags);
1266 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001267 }
1268
John McCall6b5a61b2011-02-07 10:33:21 +00001269 cleanups.ForceCleanup();
1270
John McCalld16c2cf2011-02-08 08:22:06 +00001271 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001272
John McCall5936e332011-02-15 09:22:45 +00001273 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001274}
1275
John McCallf0c11f72011-03-31 08:03:29 +00001276namespace {
1277
1278/// Emits the copy/dispose helper functions for a __block object of id type.
1279class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1280 BlockFieldFlags Flags;
1281
1282public:
1283 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1284 : ByrefHelpers(alignment), Flags(flags) {}
1285
John McCall36170192011-03-31 09:19:20 +00001286 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1287 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001288 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1289
1290 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1291 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1292
1293 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1294
1295 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1296 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1297 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1298 }
1299
1300 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1301 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1302 llvm::Value *value = CGF.Builder.CreateLoad(field);
1303
1304 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1305 }
1306
1307 void profileImpl(llvm::FoldingSetNodeID &id) const {
1308 id.AddInteger(Flags.getBitMask());
1309 }
1310};
1311
John McCallf85e1932011-06-15 23:02:42 +00001312/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1313class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1314public:
1315 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1316
1317 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1318 llvm::Value *srcField) {
1319 CGF.EmitARCMoveWeak(destField, srcField);
1320 }
1321
1322 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1323 CGF.EmitARCDestroyWeak(field);
1324 }
1325
1326 void profileImpl(llvm::FoldingSetNodeID &id) const {
1327 // 0 is distinguishable from all pointers and byref flags
1328 id.AddInteger(0);
1329 }
1330};
1331
1332/// Emits the copy/dispose helpers for an ARC __block __strong variable
1333/// that's not of block-pointer type.
1334class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1335public:
1336 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1337
1338 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1339 llvm::Value *srcField) {
1340 // Do a "move" by copying the value and then zeroing out the old
1341 // variable.
1342
1343 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1344 llvm::Value *null =
1345 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1346 CGF.Builder.CreateStore(value, destField);
1347 CGF.Builder.CreateStore(null, srcField);
1348 }
1349
1350 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1351 llvm::Value *value = CGF.Builder.CreateLoad(field);
1352 CGF.EmitARCRelease(value, /*precise*/ false);
1353 }
1354
1355 void profileImpl(llvm::FoldingSetNodeID &id) const {
1356 // 1 is distinguishable from all pointers and byref flags
1357 id.AddInteger(1);
1358 }
1359};
1360
John McCallf0c11f72011-03-31 08:03:29 +00001361/// Emits the copy/dispose helpers for a __block variable with a
1362/// nontrivial copy constructor or destructor.
1363class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1364 QualType VarType;
1365 const Expr *CopyExpr;
1366
1367public:
1368 CXXByrefHelpers(CharUnits alignment, QualType type,
1369 const Expr *copyExpr)
1370 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1371
1372 bool needsCopy() const { return CopyExpr != 0; }
1373 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1374 llvm::Value *srcField) {
1375 if (!CopyExpr) return;
1376 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1377 }
1378
1379 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1380 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1381 CGF.PushDestructorCleanup(VarType, field);
1382 CGF.PopCleanupBlocks(cleanupDepth);
1383 }
1384
1385 void profileImpl(llvm::FoldingSetNodeID &id) const {
1386 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1387 }
1388};
1389} // end anonymous namespace
1390
1391static llvm::Constant *
1392generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001393 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001394 CodeGenModule::ByrefHelpers &byrefInfo) {
1395 ASTContext &Context = CGF.getContext();
1396
1397 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001398
John McCalld26bc762011-03-09 04:27:21 +00001399 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001400 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001401 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001402
John McCallf0c11f72011-03-31 08:03:29 +00001403 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001404 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Mike Stump45031c02009-03-06 02:29:21 +00001406 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001407 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001408
John McCallf0c11f72011-03-31 08:03:29 +00001409 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001410 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001411
Mike Stump3899a7f2009-06-05 23:26:36 +00001412 // FIXME: We'd like to put these into a mergable by content, with
1413 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001414 llvm::Function *Fn =
1415 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001416 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001417
1418 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001419 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001420
John McCallf0c11f72011-03-31 08:03:29 +00001421 FunctionDecl *FD = FunctionDecl::Create(Context,
1422 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001423 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001424 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001425 SC_Static,
1426 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001427 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001428
John McCallf0c11f72011-03-31 08:03:29 +00001429 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001430
John McCallf0c11f72011-03-31 08:03:29 +00001431 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001432 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001433
John McCallf0c11f72011-03-31 08:03:29 +00001434 // dst->x
1435 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1436 destField = CGF.Builder.CreateLoad(destField);
1437 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1438 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001439
John McCallf0c11f72011-03-31 08:03:29 +00001440 // src->x
1441 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1442 srcField = CGF.Builder.CreateLoad(srcField);
1443 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1444 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1445
1446 byrefInfo.emitCopy(CGF, destField, srcField);
1447 }
1448
1449 CGF.FinishFunction();
1450
1451 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001452}
1453
John McCallf0c11f72011-03-31 08:03:29 +00001454/// Build the copy helper for a __block variable.
1455static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001456 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001457 CodeGenModule::ByrefHelpers &info) {
1458 CodeGenFunction CGF(CGM);
1459 return generateByrefCopyHelper(CGF, byrefType, info);
1460}
1461
1462/// Generate code for a __block variable's dispose helper.
1463static llvm::Constant *
1464generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001465 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001466 CodeGenModule::ByrefHelpers &byrefInfo) {
1467 ASTContext &Context = CGF.getContext();
1468 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001469
John McCalld26bc762011-03-09 04:27:21 +00001470 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001471 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001472 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Mike Stump45031c02009-03-06 02:29:21 +00001474 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001475 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001476
John McCallf0c11f72011-03-31 08:03:29 +00001477 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001478 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001479
Mike Stump3899a7f2009-06-05 23:26:36 +00001480 // FIXME: We'd like to put these into a mergable by content, with
1481 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001482 llvm::Function *Fn =
1483 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001484 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001485 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001486
1487 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001488 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001489
John McCallf0c11f72011-03-31 08:03:29 +00001490 FunctionDecl *FD = FunctionDecl::Create(Context,
1491 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001492 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001493 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001494 SC_Static,
1495 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001496 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001497 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001498
John McCallf0c11f72011-03-31 08:03:29 +00001499 if (byrefInfo.needsDispose()) {
1500 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1501 V = CGF.Builder.CreateLoad(V);
1502 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1503 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001504
John McCallf0c11f72011-03-31 08:03:29 +00001505 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001506 }
Mike Stump45031c02009-03-06 02:29:21 +00001507
John McCallf0c11f72011-03-31 08:03:29 +00001508 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001509
John McCallf0c11f72011-03-31 08:03:29 +00001510 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001511}
1512
John McCallf0c11f72011-03-31 08:03:29 +00001513/// Build the dispose helper for a __block variable.
1514static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001515 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001516 CodeGenModule::ByrefHelpers &info) {
1517 CodeGenFunction CGF(CGM);
1518 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001519}
1520
John McCallf0c11f72011-03-31 08:03:29 +00001521///
1522template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001523 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001524 T &byrefInfo) {
1525 // Increase the field's alignment to be at least pointer alignment,
1526 // since the layout of the byref struct will guarantee at least that.
1527 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1528 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1529
1530 llvm::FoldingSetNodeID id;
1531 byrefInfo.Profile(id);
1532
1533 void *insertPos;
1534 CodeGenModule::ByrefHelpers *node
1535 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1536 if (node) return static_cast<T*>(node);
1537
1538 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1539 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1540
1541 T *copy = new (CGM.getContext()) T(byrefInfo);
1542 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1543 return copy;
1544}
1545
1546CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001547CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001548 const AutoVarEmission &emission) {
1549 const VarDecl &var = *emission.Variable;
1550 QualType type = var.getType();
1551
1552 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1553 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1554 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1555
1556 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1557 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1558 }
1559
John McCallf85e1932011-06-15 23:02:42 +00001560 // Otherwise, if we don't have a retainable type, there's nothing to do.
1561 // that the runtime does extra copies.
1562 if (!type->isObjCRetainableType()) return 0;
1563
1564 Qualifiers qs = type.getQualifiers();
1565
1566 // If we have lifetime, that dominates.
1567 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1568 assert(getLangOptions().ObjCAutoRefCount);
1569
1570 switch (lifetime) {
1571 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1572
1573 // These are just bits as far as the runtime is concerned.
1574 case Qualifiers::OCL_ExplicitNone:
1575 case Qualifiers::OCL_Autoreleasing:
1576 return 0;
1577
1578 // Tell the runtime that this is ARC __weak, called by the
1579 // byref routines.
1580 case Qualifiers::OCL_Weak: {
1581 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1582 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1583 }
1584
1585 // ARC __strong __block variables need to be retained.
1586 case Qualifiers::OCL_Strong:
1587 // Block-pointers need to be _Block_copy'ed, so we let the
1588 // runtime be in charge. But we can't use the code below
1589 // because we don't want to set BYREF_CALLER, which will
1590 // just make the runtime ignore us.
1591 if (type->isBlockPointerType()) {
1592 BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
1593 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1594 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1595
1596 // Otherwise, we transfer ownership of the retain from the stack
1597 // to the heap.
1598 } else {
1599 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1600 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1601 }
1602 }
1603 llvm_unreachable("fell out of lifetime switch!");
1604 }
1605
John McCallf0c11f72011-03-31 08:03:29 +00001606 BlockFieldFlags flags;
1607 if (type->isBlockPointerType()) {
1608 flags |= BLOCK_FIELD_IS_BLOCK;
1609 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1610 type->isObjCObjectPointerType()) {
1611 flags |= BLOCK_FIELD_IS_OBJECT;
1612 } else {
1613 return 0;
1614 }
1615
1616 if (type.isObjCGCWeak())
1617 flags |= BLOCK_FIELD_IS_WEAK;
1618
1619 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1620 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001621}
1622
John McCall5af02db2011-03-31 01:59:53 +00001623unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1624 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1625
1626 return ByRefValueInfo.find(VD)->second.second;
1627}
1628
1629llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1630 const VarDecl *V) {
1631 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1632 Loc = Builder.CreateLoad(Loc);
1633 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1634 V->getNameAsString());
1635 return Loc;
1636}
1637
1638/// BuildByRefType - This routine changes a __block variable declared as T x
1639/// into:
1640///
1641/// struct {
1642/// void *__isa;
1643/// void *__forwarding;
1644/// int32_t __flags;
1645/// int32_t __size;
1646/// void *__copy_helper; // only if needed
1647/// void *__destroy_helper; // only if needed
1648/// char padding[X]; // only if needed
1649/// T x;
1650/// } x
1651///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001652llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1653 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001654 if (Info.first)
1655 return Info.first;
1656
1657 QualType Ty = D->getType();
1658
Chris Lattner5f9e2722011-07-23 10:55:15 +00001659 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001660
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001661 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001662 llvm::StructType::create(getLLVMContext(),
1663 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001664
1665 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001666 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001667
1668 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001669 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001670
1671 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001672 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001673
1674 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001675 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001676
1677 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1678 if (HasCopyAndDispose) {
1679 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001680 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001681
1682 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001683 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001684 }
1685
1686 bool Packed = false;
1687 CharUnits Align = getContext().getDeclAlign(D);
1688 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1689 // We have to insert padding.
1690
1691 // The struct above has 2 32-bit integers.
1692 unsigned CurrentOffsetInBytes = 4 * 2;
1693
1694 // And either 2 or 4 pointers.
1695 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1696 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1697
1698 // Align the offset.
1699 unsigned AlignedOffsetInBytes =
1700 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1701
1702 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1703 if (NumPaddingBytes > 0) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001704 llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
John McCall5af02db2011-03-31 01:59:53 +00001705 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001706 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001707 if (NumPaddingBytes > 1)
1708 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1709
John McCall0774cb82011-05-15 01:53:33 +00001710 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001711
1712 // We want a packed struct.
1713 Packed = true;
1714 }
1715 }
1716
1717 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001718 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001719
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001720 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001721
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001722 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001723
John McCall0774cb82011-05-15 01:53:33 +00001724 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001725
1726 return Info.first;
1727}
1728
1729/// Initialize the structural components of a __block variable, i.e.
1730/// everything but the actual object.
1731void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001732 // Find the address of the local.
1733 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001734
John McCallf0c11f72011-03-31 08:03:29 +00001735 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001736 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001737 cast<llvm::PointerType>(addr->getType())->getElementType());
1738
1739 // Build the byref helpers if necessary. This is null if we don't need any.
1740 CodeGenModule::ByrefHelpers *helpers =
1741 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001742
1743 const VarDecl &D = *emission.Variable;
1744 QualType type = D.getType();
1745
John McCallf0c11f72011-03-31 08:03:29 +00001746 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001747
1748 // Initialize the 'isa', which is just 0 or 1.
1749 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001750 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001751 isa = 1;
1752 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1753 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1754
1755 // Store the address of the variable into its own forwarding pointer.
1756 Builder.CreateStore(addr,
1757 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1758
1759 // Blocks ABI:
1760 // c) the flags field is set to either 0 if no helper functions are
1761 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1762 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001763 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001764 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1765 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1766
John McCallf0c11f72011-03-31 08:03:29 +00001767 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1768 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001769 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1770
John McCallf0c11f72011-03-31 08:03:29 +00001771 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001772 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001773 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001774
1775 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001776 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001777 }
1778}
1779
John McCalld16c2cf2011-02-08 08:22:06 +00001780void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001781 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001782 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001783 V = Builder.CreateBitCast(V, Int8PtrTy);
1784 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001785 Builder.CreateCall2(F, V, N);
1786}
John McCall5af02db2011-03-31 01:59:53 +00001787
1788namespace {
1789 struct CallBlockRelease : EHScopeStack::Cleanup {
1790 llvm::Value *Addr;
1791 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1792
John McCallad346f42011-07-12 20:27:29 +00001793 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001794 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001795 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1796 }
1797 };
1798}
1799
1800/// Enter a cleanup to destroy a __block variable. Note that this
1801/// cleanup should be a no-op if the variable hasn't left the stack
1802/// yet; if a cleanup is required for the variable itself, that needs
1803/// to be done externally.
1804void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1805 // We don't enter this cleanup if we're in pure-GC mode.
Douglas Gregore289d812011-09-13 17:21:33 +00001806 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001807 return;
1808
1809 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1810}
John McCall13db5cf2011-09-09 20:41:01 +00001811
1812/// Adjust the declaration of something from the blocks API.
1813static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1814 llvm::Constant *C) {
1815 if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1816
1817 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1818 if (GV->isDeclaration() &&
1819 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1820 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1821}
1822
1823llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1824 if (BlockObjectDispose)
1825 return BlockObjectDispose;
1826
1827 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1828 llvm::FunctionType *fty
1829 = llvm::FunctionType::get(VoidTy, args, false);
1830 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1831 configureBlocksRuntimeObject(*this, BlockObjectDispose);
1832 return BlockObjectDispose;
1833}
1834
1835llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1836 if (BlockObjectAssign)
1837 return BlockObjectAssign;
1838
1839 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1840 llvm::FunctionType *fty
1841 = llvm::FunctionType::get(VoidTy, args, false);
1842 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1843 configureBlocksRuntimeObject(*this, BlockObjectAssign);
1844 return BlockObjectAssign;
1845}
1846
1847llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1848 if (NSConcreteGlobalBlock)
1849 return NSConcreteGlobalBlock;
1850
1851 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
1852 Int8PtrTy->getPointerTo(), 0);
1853 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
1854 return NSConcreteGlobalBlock;
1855}
1856
1857llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
1858 if (NSConcreteStackBlock)
1859 return NSConcreteStackBlock;
1860
1861 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
1862 Int8PtrTy->getPointerTo(), 0);
1863 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
1864 return NSConcreteStackBlock;
1865}