blob: 19262ec54f6ef69188fcc3873e798fca5fac306a [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
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000383 bool IsRValReference = variable->getType()->isRValueReferenceType();
384 QualType VT =
385 IsRValReference ? variable->getType()->getPointeeType()
386 : variable->getType();
387 CharUnits size = C.getTypeSizeInChars(VT);
388 CharUnits align = C.getDeclAlign(variable, IsRValReference);
389
John McCall6b5a61b2011-02-07 10:33:21 +0000390 maxFieldAlign = std::max(maxFieldAlign, align);
391
Jay Foadef6de3d2011-07-11 09:56:20 +0000392 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000393 CGM.getTypes().ConvertTypeForMem(VT);
394
John McCall6b5a61b2011-02-07 10:33:21 +0000395 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
396 }
397
398 // If that was everything, we're done here.
399 if (layout.empty()) {
400 info.StructureType =
401 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
402 info.CanBeGlobal = true;
403 return;
404 }
405
406 // Sort the layout by alignment. We have to use a stable sort here
407 // to get reproducible results. There should probably be an
408 // llvm::array_pod_stable_sort.
409 std::stable_sort(layout.begin(), layout.end());
410
411 CharUnits &blockSize = info.BlockSize;
412 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
413
414 // Assuming that the first byte in the header is maximally aligned,
415 // get the alignment of the first byte following the header.
416 CharUnits endAlign = getLowBit(blockSize);
417
418 // If the end of the header isn't satisfactorily aligned for the
419 // maximum thing, look for things that are okay with the header-end
420 // alignment, and keep appending them until we get something that's
421 // aligned right. This algorithm is only guaranteed optimal if
422 // that condition is satisfied at some point; otherwise we can get
423 // things like:
424 // header // next byte has alignment 4
425 // something_with_size_5; // next byte has alignment 1
426 // something_with_alignment_8;
427 // which has 7 bytes of padding, as opposed to the naive solution
428 // which might have less (?).
429 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000431 li = layout.begin() + 1, le = layout.end();
432
433 // Look for something that the header end is already
434 // satisfactorily aligned for.
435 for (; li != le && endAlign < li->Alignment; ++li)
436 ;
437
438 // If we found something that's naturally aligned for the end of
439 // the header, keep adding things...
440 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000442 for (; li != le; ++li) {
443 assert(endAlign >= li->Alignment);
444
445 li->setIndex(info, elementTypes.size());
446 elementTypes.push_back(li->Type);
447 blockSize += li->Size;
448 endAlign = getLowBit(blockSize);
449
450 // ...until we get to the alignment of the maximum field.
451 if (endAlign >= maxFieldAlign)
452 break;
453 }
454
455 // Don't re-append everything we just appended.
456 layout.erase(first, li);
457 }
458 }
459
460 // At this point, we just have to add padding if the end align still
461 // isn't aligned right.
462 if (endAlign < maxFieldAlign) {
463 CharUnits padding = maxFieldAlign - endAlign;
464
John McCall5936e332011-02-15 09:22:45 +0000465 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
466 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000467 blockSize += padding;
468
469 endAlign = getLowBit(blockSize);
470 assert(endAlign >= maxFieldAlign);
471 }
472
473 // Slam everything else on now. This works because they have
474 // strictly decreasing alignment and we expect that size is always a
475 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000476 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000477 li = layout.begin(), le = layout.end(); li != le; ++li) {
478 assert(endAlign >= li->Alignment);
479 li->setIndex(info, elementTypes.size());
480 elementTypes.push_back(li->Type);
481 blockSize += li->Size;
482 endAlign = getLowBit(blockSize);
483 }
484
485 info.StructureType =
486 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
487}
488
489/// Emit a block literal expression in the current function.
490llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
491 std::string Name = CurFn->getName();
492 CGBlockInfo blockInfo(blockExpr, Name.c_str());
493
494 // Compute information about the layout, etc., of this block.
495 computeBlockInfo(CGM, blockInfo);
496
497 // Using that metadata, generate the actual block function.
498 llvm::Constant *blockFn
499 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
500 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000501 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000502
503 // If there is nothing to capture, we can emit this as a global block.
504 if (blockInfo.CanBeGlobal)
505 return buildGlobalBlock(CGM, blockInfo, blockFn);
506
507 // Otherwise, we have to emit this as a local block.
508
509 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000510 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000511
512 // Build the block descriptor.
513 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
514
Chris Lattner2acc6e32011-07-18 04:24:23 +0000515 llvm::Type *intTy = ConvertType(getContext().IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000516
517 llvm::AllocaInst *blockAddr =
518 CreateTempAlloca(blockInfo.StructureType, "block");
519 blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
520
521 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000522 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000523 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
524 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000525 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000526
527 // Initialize the block literal.
528 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCalld16c2cf2011-02-08 08:22:06 +0000529 Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000530 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
531 Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
532 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
533 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
534 "block.invoke"));
535 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
536 "block.descriptor"));
537
538 // Finally, capture all the values into the block.
539 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
540
541 // First, 'this'.
542 if (blockDecl->capturesCXXThis()) {
543 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
544 blockInfo.CXXThisIndex,
545 "block.captured-this.addr");
546 Builder.CreateStore(LoadCXXThis(), addr);
547 }
548
549 // Next, captured variables.
550 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
551 ce = blockDecl->capture_end(); ci != ce; ++ci) {
552 const VarDecl *variable = ci->getVariable();
553 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
554
555 // Ignore constant captures.
556 if (capture.isConstant()) continue;
557
558 QualType type = variable->getType();
559
560 // This will be a [[type]]*, except that a byref entry will just be
561 // an i8**.
562 llvm::Value *blockField =
563 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
564 "block.captured");
565
566 // Compute the address of the thing we're going to move into the
567 // block literal.
568 llvm::Value *src;
569 if (ci->isNested()) {
570 // We need to use the capture from the enclosing block.
571 const CGBlockInfo::Capture &enclosingCapture =
572 BlockInfo->getCapture(variable);
573
574 // This is a [[type]]*, except that a byref entry wil just be an i8**.
575 src = Builder.CreateStructGEP(LoadBlockStruct(),
576 enclosingCapture.getIndex(),
577 "block.capture.addr");
578 } else {
579 // This is a [[type]]*.
580 src = LocalDeclMap[variable];
581 }
582
583 // For byrefs, we just write the pointer to the byref struct into
584 // the block field. There's no need to chase the forwarding
585 // pointer at this point, since we're building something that will
586 // live a shorter life than the stack byref anyway.
587 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000588 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000589 if (ci->isNested())
590 src = Builder.CreateLoad(src, "byref.capture");
591 else
John McCall5936e332011-02-15 09:22:45 +0000592 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000593
John McCall5936e332011-02-15 09:22:45 +0000594 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000595 Builder.CreateStore(src, blockField);
596
597 // If we have a copy constructor, evaluate that into the block field.
598 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
599 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
600
601 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000602 } else if (type->isReferenceType() && !type->isRValueReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000603 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
604
605 // Otherwise, fake up a POD copy into the block field.
606 } else {
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000607 QualType VT =
608 (!type->isRValueReferenceType()) ? type : type->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +0000609 // Fake up a new variable so that EmitScalarInit doesn't think
610 // we're referring to the variable in its own initializer.
611 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000612 /*name*/ 0, VT);
John McCallf85e1932011-06-15 23:02:42 +0000613
John McCallbb699b02011-02-07 18:37:40 +0000614 // We use one of these or the other depending on whether the
615 // reference is nested.
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000616 DeclRefExpr notNested(const_cast<VarDecl*>(variable), VT, VK_LValue,
John McCallbb699b02011-02-07 18:37:40 +0000617 SourceLocation());
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000618 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), VT,
John McCallbb699b02011-02-07 18:37:40 +0000619 VK_LValue, SourceLocation(), /*byref*/ false);
620
621 Expr *declRef =
622 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
623
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000624 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, VT, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000625 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000626 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000627 MakeAddrLValue(blockField, VT,
Eli Friedman225bf772011-09-30 18:19:16 +0000628 getContext().getDeclAlign(variable)
629 .getQuantity()),
John McCalldf045202011-03-08 09:38:48 +0000630 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000631 }
632
633 // Push a destructor if necessary. The semantics for when this
634 // actually gets run are really obscure.
John McCallf85e1932011-06-15 23:02:42 +0000635 if (!ci->isByRef()) {
John McCall9928c482011-07-12 16:41:08 +0000636 switch (QualType::DestructionKind dtorKind = type.isDestructedType()) {
John McCallf85e1932011-06-15 23:02:42 +0000637 case QualType::DK_none:
638 break;
John McCall9928c482011-07-12 16:41:08 +0000639
640 // Block captures count as local values and have imprecise semantics.
641 // They also can't be arrays, so need to worry about that.
John McCall5bcd95e2011-07-12 16:53:04 +0000642 case QualType::DK_objc_strong_lifetime: {
643 // This local is a GCC and MSVC compiler workaround.
644 Destroyer *destroyer = &destroyARCStrongImprecise;
John McCall9928c482011-07-12 16:41:08 +0000645 pushDestroy(getCleanupKind(dtorKind), blockField, type,
John McCall5bcd95e2011-07-12 16:53:04 +0000646 *destroyer, /*useEHCleanupForArray*/ false);
John McCallf85e1932011-06-15 23:02:42 +0000647 break;
John McCall5bcd95e2011-07-12 16:53:04 +0000648 }
John McCall9928c482011-07-12 16:41:08 +0000649
John McCallf85e1932011-06-15 23:02:42 +0000650 case QualType::DK_objc_weak_lifetime:
John McCall9928c482011-07-12 16:41:08 +0000651 case QualType::DK_cxx_destructor:
652 pushDestroy(dtorKind, blockField, type);
John McCallf85e1932011-06-15 23:02:42 +0000653 break;
654 }
655 }
John McCall6b5a61b2011-02-07 10:33:21 +0000656 }
657
658 // Cast to the converted block-pointer type, which happens (somewhat
659 // unfortunately) to be a pointer to function type.
660 llvm::Value *result =
661 Builder.CreateBitCast(blockAddr,
662 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000663
John McCall6b5a61b2011-02-07 10:33:21 +0000664 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000665}
666
667
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000668llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000669 if (BlockDescriptorType)
670 return BlockDescriptorType;
671
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000672 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000673 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000674
Mike Stumpab695142009-02-13 15:16:56 +0000675 // struct __block_descriptor {
676 // unsigned long reserved;
677 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000678 //
679 // // later, the following will be added
680 //
681 // struct {
682 // void (*copyHelper)();
683 // void (*copyHelper)();
684 // } helpers; // !!! optional
685 //
686 // const char *signature; // the block signature
687 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000688 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000689 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000690 llvm::StructType::create("struct.__block_descriptor",
691 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000692
John McCall6b5a61b2011-02-07 10:33:21 +0000693 // Now form a pointer to that.
694 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000695 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000696}
697
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000698llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000699 if (GenericBlockLiteralType)
700 return GenericBlockLiteralType;
701
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000702 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000703
Mike Stump9b8a7972009-02-13 15:25:34 +0000704 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000705 // void *__isa;
706 // int __flags;
707 // int __reserved;
708 // void (*__invoke)(void *);
709 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000710 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000711 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000712 llvm::StructType::create("struct.__block_literal_generic",
713 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
714 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000715
Mike Stump9b8a7972009-02-13 15:25:34 +0000716 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000717}
718
Mike Stumpbd65cac2009-02-19 01:01:04 +0000719
Anders Carlssona1736c02009-12-24 21:13:40 +0000720RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
721 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000722 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000723 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000724
Anders Carlssonacfde802009-02-12 00:39:25 +0000725 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
726
727 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000728 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000729 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000730
731 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000732 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000733 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
734
735 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000736 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000737
Benjamin Kramer578faa82011-09-27 21:06:10 +0000738 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000739
Anders Carlssonacfde802009-02-12 00:39:25 +0000740 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000741 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000742 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000743
Anders Carlsson782f3972009-04-08 23:13:16 +0000744 QualType FnType = BPT->getPointeeType();
745
Anders Carlssonacfde802009-02-12 00:39:25 +0000746 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000747 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000748 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000749
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000750 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000751 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000752
John McCall64cd2322011-03-09 08:39:33 +0000753 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
Eli Friedmanc55db3b2011-08-09 17:38:12 +0000754 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000756 // Cast the function pointer to the right type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000757 llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000758 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattner2acc6e32011-07-18 04:24:23 +0000760 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000761 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Anders Carlssonacfde802009-02-12 00:39:25 +0000763 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000764 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000765}
Anders Carlssond5cab542009-02-12 17:55:02 +0000766
John McCall6b5a61b2011-02-07 10:33:21 +0000767llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
768 bool isByRef) {
769 assert(BlockInfo && "evaluating block ref without block information?");
770 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000771
John McCall6b5a61b2011-02-07 10:33:21 +0000772 // Handle constant captures.
773 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000774
John McCall6b5a61b2011-02-07 10:33:21 +0000775 llvm::Value *addr =
776 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
777 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000778
John McCall6b5a61b2011-02-07 10:33:21 +0000779 if (isByRef) {
780 // addr should be a void** right now. Load, then cast the result
781 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000782
John McCall6b5a61b2011-02-07 10:33:21 +0000783 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000784 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000785 = llvm::PointerType::get(BuildByRefType(variable), 0);
786 addr = Builder.CreateBitCast(addr, byrefPointerType,
787 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000788
John McCall6b5a61b2011-02-07 10:33:21 +0000789 // Follow the forwarding pointer.
790 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
791 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000792
John McCall6b5a61b2011-02-07 10:33:21 +0000793 // Cast back to byref* and GEP over to the actual object.
794 addr = Builder.CreateBitCast(addr, byrefPointerType);
795 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
796 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000797 }
798
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000799 if (variable->getType()->isReferenceType() &&
800 !variable->getType()->isRValueReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000801 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000802
John McCall6b5a61b2011-02-07 10:33:21 +0000803 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000804}
805
Mike Stump67a64482009-02-14 22:16:35 +0000806llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000807CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000808 const char *name) {
John McCall6b5a61b2011-02-07 10:33:21 +0000809 CGBlockInfo blockInfo(blockExpr, name);
Mike Stumpa5448542009-02-13 15:32:32 +0000810
John McCall6b5a61b2011-02-07 10:33:21 +0000811 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000812 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000813
John McCall6b5a61b2011-02-07 10:33:21 +0000814 // Using that metadata, generate the actual block function.
815 llvm::Constant *blockFn;
816 {
817 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000818 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
819 blockInfo,
820 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000821 }
John McCall5936e332011-02-15 09:22:45 +0000822 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000823
John McCalld16c2cf2011-02-08 08:22:06 +0000824 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000825}
826
John McCall6b5a61b2011-02-07 10:33:21 +0000827static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
828 const CGBlockInfo &blockInfo,
829 llvm::Constant *blockFn) {
830 assert(blockInfo.CanBeGlobal);
831
832 // Generate the constants for the block literal initializer.
833 llvm::Constant *fields[BlockHeaderSize];
834
835 // isa
836 fields[0] = CGM.getNSConcreteGlobalBlock();
837
838 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000839 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
840 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
841
John McCall5936e332011-02-15 09:22:45 +0000842 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000843
844 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000845 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000846
847 // Function
848 fields[3] = blockFn;
849
850 // Descriptor
851 fields[4] = buildBlockDescriptor(CGM, blockInfo);
852
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000853 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000854
855 llvm::GlobalVariable *literal =
856 new llvm::GlobalVariable(CGM.getModule(),
857 init->getType(),
858 /*constant*/ true,
859 llvm::GlobalVariable::InternalLinkage,
860 init,
861 "__block_literal_global");
862 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
863
864 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000865 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000866 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
867 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000868}
869
Mike Stump00470a12009-03-05 08:32:30 +0000870llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000871CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
872 const CGBlockInfo &blockInfo,
873 const Decl *outerFnDecl,
874 const DeclMapTy &ldm) {
875 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000876
Devang Patel6d1155b2011-03-07 21:53:18 +0000877 // Check if we should generate debug info for this block function.
878 if (CGM.getModuleDebugInfo())
879 DebugInfo = CGM.getModuleDebugInfo();
880
John McCall6b5a61b2011-02-07 10:33:21 +0000881 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Mike Stump7f28a9c2009-03-13 23:34:28 +0000883 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000884 // to be local to this function as well, in case they're directly
885 // referenced in a block.
886 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
887 const VarDecl *var = dyn_cast<VarDecl>(i->first);
888 if (var && !var->hasLocalStorage())
889 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000890 }
891
John McCall6b5a61b2011-02-07 10:33:21 +0000892 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000893
John McCall6b5a61b2011-02-07 10:33:21 +0000894 // Build the argument list.
895 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000896
John McCall6b5a61b2011-02-07 10:33:21 +0000897 // The first argument is the block pointer. Just take it as a void*
898 // and cast it later.
899 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +0000900 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000901
John McCall8178df32011-02-22 22:38:33 +0000902 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
903 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +0000904 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +0000905
John McCall6b5a61b2011-02-07 10:33:21 +0000906 // Now add the rest of the parameters.
907 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
908 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +0000909 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911 // Create the function declaration.
912 const FunctionProtoType *fnType =
913 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
914 const CGFunctionInfo &fnInfo =
915 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
916 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +0000917 if (CGM.ReturnTypeUsesSRet(fnInfo))
918 blockInfo.UsesStret = true;
919
Chris Lattner2acc6e32011-07-18 04:24:23 +0000920 llvm::FunctionType *fnLLVMType =
John McCall6b5a61b2011-02-07 10:33:21 +0000921 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000922
John McCall6b5a61b2011-02-07 10:33:21 +0000923 MangleBuffer name;
924 CGM.getBlockMangledName(GD, name, blockDecl);
925 llvm::Function *fn =
926 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
927 name.getString(), &CGM.getModule());
928 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000929
John McCall6b5a61b2011-02-07 10:33:21 +0000930 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +0000931 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +0000932 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +0000933 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +0000934
John McCall8178df32011-02-22 22:38:33 +0000935 // Okay. Undo some of what StartFunction did.
936
937 // Pull the 'self' reference out of the local decl map.
938 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
939 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +0000940 BlockPointer = Builder.CreateBitCast(blockAddr,
941 blockInfo.StructureType->getPointerTo(),
942 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +0000943
John McCallea1471e2010-05-20 01:18:31 +0000944 // If we have a C++ 'this' reference, go ahead and force it into
945 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +0000946 if (blockDecl->capturesCXXThis()) {
947 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
948 blockInfo.CXXThisIndex,
949 "block.captured-this");
950 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +0000951 }
952
John McCall6b5a61b2011-02-07 10:33:21 +0000953 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
954 // appease it.
955 if (const ObjCMethodDecl *method
956 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
957 const VarDecl *self = method->getSelfDecl();
958
959 // There might not be a capture for 'self', but if there is...
960 if (blockInfo.Captures.count(self)) {
961 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
962 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
963 capture.getIndex(),
964 "block.captured-self");
965 LocalDeclMap[self] = selfAddr;
966 }
967 }
968
969 // Also force all the constant captures.
970 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
971 ce = blockDecl->capture_end(); ci != ce; ++ci) {
972 const VarDecl *variable = ci->getVariable();
973 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
974 if (!capture.isConstant()) continue;
975
976 unsigned align = getContext().getDeclAlign(variable).getQuantity();
977
978 llvm::AllocaInst *alloca =
979 CreateMemTemp(variable->getType(), "block.captured-const");
980 alloca->setAlignment(align);
981
982 Builder.CreateStore(capture.getConstant(), alloca, align);
983
984 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +0000985 }
986
Mike Stumpb289b3f2009-10-01 22:29:41 +0000987 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
988 llvm::BasicBlock *entry = Builder.GetInsertBlock();
989 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
990 --entry_ptr;
991
John McCall6b5a61b2011-02-07 10:33:21 +0000992 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000993
Mike Stumpde8c5c72009-10-01 00:27:30 +0000994 // Remember where we were...
995 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000996
Mike Stumpde8c5c72009-10-01 00:27:30 +0000997 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000998 ++entry_ptr;
999 Builder.SetInsertPoint(entry, entry_ptr);
1000
John McCall6b5a61b2011-02-07 10:33:21 +00001001 // Emit debug information for all the BlockDeclRefDecls.
1002 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001003 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001004 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1005 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1006 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001007 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001008
1009 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1010 if (capture.isConstant()) {
1011 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1012 Builder);
1013 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001014 }
John McCall6b5a61b2011-02-07 10:33:21 +00001015
John McCall8178df32011-02-22 22:38:33 +00001016 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001017 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001018 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001019 }
John McCall6b5a61b2011-02-07 10:33:21 +00001020
Mike Stumpde8c5c72009-10-01 00:27:30 +00001021 // And resume where we left off.
1022 if (resume == 0)
1023 Builder.ClearInsertionPoint();
1024 else
1025 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001026
John McCall6b5a61b2011-02-07 10:33:21 +00001027 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001028
John McCall6b5a61b2011-02-07 10:33:21 +00001029 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001030}
Mike Stumpa99038c2009-02-28 09:07:16 +00001031
John McCall6b5a61b2011-02-07 10:33:21 +00001032/*
1033 notes.push_back(HelperInfo());
1034 HelperInfo &note = notes.back();
1035 note.index = capture.getIndex();
1036 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1037 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001038
John McCall6b5a61b2011-02-07 10:33:21 +00001039 if (ci->isByRef()) {
1040 note.flag = BLOCK_FIELD_IS_BYREF;
1041 if (type.isObjCGCWeak())
1042 note.flag |= BLOCK_FIELD_IS_WEAK;
1043 } else if (type->isBlockPointerType()) {
1044 note.flag = BLOCK_FIELD_IS_BLOCK;
1045 } else {
1046 note.flag = BLOCK_FIELD_IS_OBJECT;
1047 }
1048 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001049
Mike Stump00470a12009-03-05 08:32:30 +00001050
Mike Stumpa99038c2009-02-28 09:07:16 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001053CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001054 ASTContext &C = getContext();
1055
1056 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001057 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1058 args.push_back(&dstDecl);
1059 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1060 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Mike Stumpa4f668f2009-03-06 01:33:24 +00001062 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001063 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001064
John McCall6b5a61b2011-02-07 10:33:21 +00001065 // FIXME: it would be nice if these were mergeable with things with
1066 // identical semantics.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001067 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001068
1069 llvm::Function *Fn =
1070 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001071 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001072
1073 IdentifierInfo *II
1074 = &CGM.getContext().Idents.get("__copy_helper_block_");
1075
Devang Patel58dc5ca2011-05-02 20:37:08 +00001076 // Check if we should generate debug info for this block helper function.
1077 if (CGM.getModuleDebugInfo())
1078 DebugInfo = CGM.getModuleDebugInfo();
1079
John McCall6b5a61b2011-02-07 10:33:21 +00001080 FunctionDecl *FD = FunctionDecl::Create(C,
1081 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001082 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001083 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001084 SC_Static,
1085 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001086 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001087 true);
John McCalld26bc762011-03-09 04:27:21 +00001088 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001089
Chris Lattner2acc6e32011-07-18 04:24:23 +00001090 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001091
John McCalld26bc762011-03-09 04:27:21 +00001092 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001093 src = Builder.CreateLoad(src);
1094 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001095
John McCalld26bc762011-03-09 04:27:21 +00001096 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001097 dst = Builder.CreateLoad(dst);
1098 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001099
John McCall6b5a61b2011-02-07 10:33:21 +00001100 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001101
John McCall6b5a61b2011-02-07 10:33:21 +00001102 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1103 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1104 const VarDecl *variable = ci->getVariable();
1105 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001106
John McCall6b5a61b2011-02-07 10:33:21 +00001107 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1108 if (capture.isConstant()) continue;
1109
1110 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001111 BlockFieldFlags flags;
1112
1113 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001114
1115 if (copyExpr) {
1116 assert(!ci->isByRef());
1117 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001118
John McCall6b5a61b2011-02-07 10:33:21 +00001119 } else if (ci->isByRef()) {
1120 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001121 if (type.isObjCGCWeak())
1122 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001123
John McCallf85e1932011-06-15 23:02:42 +00001124 } else if (type->isObjCRetainableType()) {
1125 flags = BLOCK_FIELD_IS_OBJECT;
1126 if (type->isBlockPointerType())
1127 flags = BLOCK_FIELD_IS_BLOCK;
1128
1129 // Special rules for ARC captures:
1130 if (getLangOptions().ObjCAutoRefCount) {
1131 Qualifiers qs = type.getQualifiers();
1132
1133 // Don't generate special copy logic for a captured object
1134 // unless it's __strong or __weak.
1135 if (!qs.hasStrongOrWeakObjCLifetime())
1136 continue;
1137
1138 // Support __weak direct captures.
1139 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1140 isARCWeakCapture = true;
1141 }
1142 } else {
1143 continue;
1144 }
John McCall6b5a61b2011-02-07 10:33:21 +00001145
1146 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001147 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1148 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001149
1150 // If there's an explicit copy expression, we do that.
1151 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001152 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001153 } else if (isARCWeakCapture) {
1154 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001155 } else {
1156 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001157 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1158 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001159 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001160 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001161 }
1162 }
1163
John McCalld16c2cf2011-02-08 08:22:06 +00001164 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001165
John McCall5936e332011-02-15 09:22:45 +00001166 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001167}
1168
John McCall6b5a61b2011-02-07 10:33:21 +00001169llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001170CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001171 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001172
John McCall6b5a61b2011-02-07 10:33:21 +00001173 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001174 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1175 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Mike Stumpa4f668f2009-03-06 01:33:24 +00001177 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001178 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001179
Mike Stump3899a7f2009-06-05 23:26:36 +00001180 // FIXME: We'd like to put these into a mergable by content, with
1181 // internal linkage.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001182 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001183
1184 llvm::Function *Fn =
1185 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001186 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001187
Devang Patel58dc5ca2011-05-02 20:37:08 +00001188 // Check if we should generate debug info for this block destroy function.
1189 if (CGM.getModuleDebugInfo())
1190 DebugInfo = CGM.getModuleDebugInfo();
1191
Mike Stumpa4f668f2009-03-06 01:33:24 +00001192 IdentifierInfo *II
1193 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1194
John McCall6b5a61b2011-02-07 10:33:21 +00001195 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001196 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001197 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001198 SC_Static,
1199 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001200 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001201 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001202
Chris Lattner2acc6e32011-07-18 04:24:23 +00001203 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001204
John McCalld26bc762011-03-09 04:27:21 +00001205 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001206 src = Builder.CreateLoad(src);
1207 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001208
John McCall6b5a61b2011-02-07 10:33:21 +00001209 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1210
John McCalld16c2cf2011-02-08 08:22:06 +00001211 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001212
1213 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1214 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1215 const VarDecl *variable = ci->getVariable();
1216 QualType type = variable->getType();
1217
1218 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1219 if (capture.isConstant()) continue;
1220
John McCalld16c2cf2011-02-08 08:22:06 +00001221 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001222 const CXXDestructorDecl *dtor = 0;
1223
John McCallf85e1932011-06-15 23:02:42 +00001224 bool isARCWeakCapture = false;
1225
John McCall6b5a61b2011-02-07 10:33:21 +00001226 if (ci->isByRef()) {
1227 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001228 if (type.isObjCGCWeak())
1229 flags |= BLOCK_FIELD_IS_WEAK;
1230 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1231 if (record->hasTrivialDestructor())
1232 continue;
1233 dtor = record->getDestructor();
1234 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001235 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001236 if (type->isBlockPointerType())
1237 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001238
John McCallf85e1932011-06-15 23:02:42 +00001239 // Special rules for ARC captures.
1240 if (getLangOptions().ObjCAutoRefCount) {
1241 Qualifiers qs = type.getQualifiers();
1242
1243 // Don't generate special dispose logic for a captured object
1244 // unless it's __strong or __weak.
1245 if (!qs.hasStrongOrWeakObjCLifetime())
1246 continue;
1247
1248 // Support __weak direct captures.
1249 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1250 isARCWeakCapture = true;
1251 }
1252 } else {
1253 continue;
1254 }
John McCall6b5a61b2011-02-07 10:33:21 +00001255
1256 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001257 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001258
1259 // If there's an explicit copy expression, we do that.
1260 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001261 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001262
John McCallf85e1932011-06-15 23:02:42 +00001263 // If this is a __weak capture, emit the release directly.
1264 } else if (isARCWeakCapture) {
1265 EmitARCDestroyWeak(srcField);
1266
John McCall6b5a61b2011-02-07 10:33:21 +00001267 // Otherwise we call _Block_object_dispose. It wouldn't be too
1268 // hard to just emit this as a cleanup if we wanted to make sure
1269 // that things were done in reverse.
1270 } else {
1271 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001272 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001273 BuildBlockRelease(value, flags);
1274 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001275 }
1276
John McCall6b5a61b2011-02-07 10:33:21 +00001277 cleanups.ForceCleanup();
1278
John McCalld16c2cf2011-02-08 08:22:06 +00001279 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001280
John McCall5936e332011-02-15 09:22:45 +00001281 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001282}
1283
John McCallf0c11f72011-03-31 08:03:29 +00001284namespace {
1285
1286/// Emits the copy/dispose helper functions for a __block object of id type.
1287class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1288 BlockFieldFlags Flags;
1289
1290public:
1291 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1292 : ByrefHelpers(alignment), Flags(flags) {}
1293
John McCall36170192011-03-31 09:19:20 +00001294 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1295 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001296 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1297
1298 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1299 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1300
1301 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1302
1303 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1304 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1305 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1306 }
1307
1308 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1309 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1310 llvm::Value *value = CGF.Builder.CreateLoad(field);
1311
1312 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1313 }
1314
1315 void profileImpl(llvm::FoldingSetNodeID &id) const {
1316 id.AddInteger(Flags.getBitMask());
1317 }
1318};
1319
John McCallf85e1932011-06-15 23:02:42 +00001320/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1321class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1322public:
1323 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1324
1325 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1326 llvm::Value *srcField) {
1327 CGF.EmitARCMoveWeak(destField, srcField);
1328 }
1329
1330 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1331 CGF.EmitARCDestroyWeak(field);
1332 }
1333
1334 void profileImpl(llvm::FoldingSetNodeID &id) const {
1335 // 0 is distinguishable from all pointers and byref flags
1336 id.AddInteger(0);
1337 }
1338};
1339
1340/// Emits the copy/dispose helpers for an ARC __block __strong variable
1341/// that's not of block-pointer type.
1342class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1343public:
1344 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1345
1346 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1347 llvm::Value *srcField) {
1348 // Do a "move" by copying the value and then zeroing out the old
1349 // variable.
1350
1351 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
1352 llvm::Value *null =
1353 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
1354 CGF.Builder.CreateStore(value, destField);
1355 CGF.Builder.CreateStore(null, srcField);
1356 }
1357
1358 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1359 llvm::Value *value = CGF.Builder.CreateLoad(field);
1360 CGF.EmitARCRelease(value, /*precise*/ false);
1361 }
1362
1363 void profileImpl(llvm::FoldingSetNodeID &id) const {
1364 // 1 is distinguishable from all pointers and byref flags
1365 id.AddInteger(1);
1366 }
1367};
1368
John McCallf0c11f72011-03-31 08:03:29 +00001369/// Emits the copy/dispose helpers for a __block variable with a
1370/// nontrivial copy constructor or destructor.
1371class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1372 QualType VarType;
1373 const Expr *CopyExpr;
1374
1375public:
1376 CXXByrefHelpers(CharUnits alignment, QualType type,
1377 const Expr *copyExpr)
1378 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1379
1380 bool needsCopy() const { return CopyExpr != 0; }
1381 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1382 llvm::Value *srcField) {
1383 if (!CopyExpr) return;
1384 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1385 }
1386
1387 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1388 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1389 CGF.PushDestructorCleanup(VarType, field);
1390 CGF.PopCleanupBlocks(cleanupDepth);
1391 }
1392
1393 void profileImpl(llvm::FoldingSetNodeID &id) const {
1394 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1395 }
1396};
1397} // end anonymous namespace
1398
1399static llvm::Constant *
1400generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001401 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001402 CodeGenModule::ByrefHelpers &byrefInfo) {
1403 ASTContext &Context = CGF.getContext();
1404
1405 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001406
John McCalld26bc762011-03-09 04:27:21 +00001407 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001408 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001409 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001410
John McCallf0c11f72011-03-31 08:03:29 +00001411 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001412 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Mike Stump45031c02009-03-06 02:29:21 +00001414 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001415 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001416
John McCallf0c11f72011-03-31 08:03:29 +00001417 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001418 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001419
Mike Stump3899a7f2009-06-05 23:26:36 +00001420 // FIXME: We'd like to put these into a mergable by content, with
1421 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001422 llvm::Function *Fn =
1423 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001424 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001425
1426 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001427 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001428
John McCallf0c11f72011-03-31 08:03:29 +00001429 FunctionDecl *FD = FunctionDecl::Create(Context,
1430 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001431 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001432 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001433 SC_Static,
1434 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001435 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001436
John McCallf0c11f72011-03-31 08:03:29 +00001437 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001438
John McCallf0c11f72011-03-31 08:03:29 +00001439 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001440 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001441
John McCallf0c11f72011-03-31 08:03:29 +00001442 // dst->x
1443 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1444 destField = CGF.Builder.CreateLoad(destField);
1445 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1446 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001447
John McCallf0c11f72011-03-31 08:03:29 +00001448 // src->x
1449 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1450 srcField = CGF.Builder.CreateLoad(srcField);
1451 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1452 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1453
1454 byrefInfo.emitCopy(CGF, destField, srcField);
1455 }
1456
1457 CGF.FinishFunction();
1458
1459 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001460}
1461
John McCallf0c11f72011-03-31 08:03:29 +00001462/// Build the copy helper for a __block variable.
1463static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001464 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001465 CodeGenModule::ByrefHelpers &info) {
1466 CodeGenFunction CGF(CGM);
1467 return generateByrefCopyHelper(CGF, byrefType, info);
1468}
1469
1470/// Generate code for a __block variable's dispose helper.
1471static llvm::Constant *
1472generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001473 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001474 CodeGenModule::ByrefHelpers &byrefInfo) {
1475 ASTContext &Context = CGF.getContext();
1476 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001477
John McCalld26bc762011-03-09 04:27:21 +00001478 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001479 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001480 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Mike Stump45031c02009-03-06 02:29:21 +00001482 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001483 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001484
John McCallf0c11f72011-03-31 08:03:29 +00001485 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001486 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001487
Mike Stump3899a7f2009-06-05 23:26:36 +00001488 // FIXME: We'd like to put these into a mergable by content, with
1489 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001490 llvm::Function *Fn =
1491 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001492 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001493 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001494
1495 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001496 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001497
John McCallf0c11f72011-03-31 08:03:29 +00001498 FunctionDecl *FD = FunctionDecl::Create(Context,
1499 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001500 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001501 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001502 SC_Static,
1503 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001504 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001505 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001506
John McCallf0c11f72011-03-31 08:03:29 +00001507 if (byrefInfo.needsDispose()) {
1508 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1509 V = CGF.Builder.CreateLoad(V);
1510 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1511 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001512
John McCallf0c11f72011-03-31 08:03:29 +00001513 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001514 }
Mike Stump45031c02009-03-06 02:29:21 +00001515
John McCallf0c11f72011-03-31 08:03:29 +00001516 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001517
John McCallf0c11f72011-03-31 08:03:29 +00001518 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001519}
1520
John McCallf0c11f72011-03-31 08:03:29 +00001521/// Build the dispose helper for a __block variable.
1522static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001523 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001524 CodeGenModule::ByrefHelpers &info) {
1525 CodeGenFunction CGF(CGM);
1526 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001527}
1528
John McCallf0c11f72011-03-31 08:03:29 +00001529///
1530template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001531 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001532 T &byrefInfo) {
1533 // Increase the field's alignment to be at least pointer alignment,
1534 // since the layout of the byref struct will guarantee at least that.
1535 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1536 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1537
1538 llvm::FoldingSetNodeID id;
1539 byrefInfo.Profile(id);
1540
1541 void *insertPos;
1542 CodeGenModule::ByrefHelpers *node
1543 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1544 if (node) return static_cast<T*>(node);
1545
1546 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1547 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1548
1549 T *copy = new (CGM.getContext()) T(byrefInfo);
1550 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1551 return copy;
1552}
1553
1554CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001555CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001556 const AutoVarEmission &emission) {
1557 const VarDecl &var = *emission.Variable;
1558 QualType type = var.getType();
1559
1560 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1561 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1562 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1563
1564 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1565 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1566 }
1567
John McCallf85e1932011-06-15 23:02:42 +00001568 // Otherwise, if we don't have a retainable type, there's nothing to do.
1569 // that the runtime does extra copies.
1570 if (!type->isObjCRetainableType()) return 0;
1571
1572 Qualifiers qs = type.getQualifiers();
1573
1574 // If we have lifetime, that dominates.
1575 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1576 assert(getLangOptions().ObjCAutoRefCount);
1577
1578 switch (lifetime) {
1579 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1580
1581 // These are just bits as far as the runtime is concerned.
1582 case Qualifiers::OCL_ExplicitNone:
1583 case Qualifiers::OCL_Autoreleasing:
1584 return 0;
1585
1586 // Tell the runtime that this is ARC __weak, called by the
1587 // byref routines.
1588 case Qualifiers::OCL_Weak: {
1589 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1590 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1591 }
1592
1593 // ARC __strong __block variables need to be retained.
1594 case Qualifiers::OCL_Strong:
1595 // Block-pointers need to be _Block_copy'ed, so we let the
1596 // runtime be in charge. But we can't use the code below
1597 // because we don't want to set BYREF_CALLER, which will
1598 // just make the runtime ignore us.
1599 if (type->isBlockPointerType()) {
1600 BlockFieldFlags flags = BLOCK_FIELD_IS_BLOCK;
1601 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1602 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1603
1604 // Otherwise, we transfer ownership of the retain from the stack
1605 // to the heap.
1606 } else {
1607 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1608 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1609 }
1610 }
1611 llvm_unreachable("fell out of lifetime switch!");
1612 }
1613
John McCallf0c11f72011-03-31 08:03:29 +00001614 BlockFieldFlags flags;
1615 if (type->isBlockPointerType()) {
1616 flags |= BLOCK_FIELD_IS_BLOCK;
1617 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1618 type->isObjCObjectPointerType()) {
1619 flags |= BLOCK_FIELD_IS_OBJECT;
1620 } else {
1621 return 0;
1622 }
1623
1624 if (type.isObjCGCWeak())
1625 flags |= BLOCK_FIELD_IS_WEAK;
1626
1627 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1628 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001629}
1630
John McCall5af02db2011-03-31 01:59:53 +00001631unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1632 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1633
1634 return ByRefValueInfo.find(VD)->second.second;
1635}
1636
1637llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1638 const VarDecl *V) {
1639 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1640 Loc = Builder.CreateLoad(Loc);
1641 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1642 V->getNameAsString());
1643 return Loc;
1644}
1645
1646/// BuildByRefType - This routine changes a __block variable declared as T x
1647/// into:
1648///
1649/// struct {
1650/// void *__isa;
1651/// void *__forwarding;
1652/// int32_t __flags;
1653/// int32_t __size;
1654/// void *__copy_helper; // only if needed
1655/// void *__destroy_helper; // only if needed
1656/// char padding[X]; // only if needed
1657/// T x;
1658/// } x
1659///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001660llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1661 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001662 if (Info.first)
1663 return Info.first;
1664
1665 QualType Ty = D->getType();
1666
Chris Lattner5f9e2722011-07-23 10:55:15 +00001667 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001668
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001669 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001670 llvm::StructType::create(getLLVMContext(),
1671 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001672
1673 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001674 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001675
1676 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001677 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001678
1679 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001680 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001681
1682 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001683 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001684
1685 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1686 if (HasCopyAndDispose) {
1687 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001688 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001689
1690 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001691 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001692 }
1693
1694 bool Packed = false;
1695 CharUnits Align = getContext().getDeclAlign(D);
1696 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1697 // We have to insert padding.
1698
1699 // The struct above has 2 32-bit integers.
1700 unsigned CurrentOffsetInBytes = 4 * 2;
1701
1702 // And either 2 or 4 pointers.
1703 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1704 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1705
1706 // Align the offset.
1707 unsigned AlignedOffsetInBytes =
1708 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1709
1710 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1711 if (NumPaddingBytes > 0) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001712 llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
John McCall5af02db2011-03-31 01:59:53 +00001713 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001714 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001715 if (NumPaddingBytes > 1)
1716 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1717
John McCall0774cb82011-05-15 01:53:33 +00001718 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001719
1720 // We want a packed struct.
1721 Packed = true;
1722 }
1723 }
1724
1725 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001726 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001727
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001728 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001729
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001730 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001731
John McCall0774cb82011-05-15 01:53:33 +00001732 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001733
1734 return Info.first;
1735}
1736
1737/// Initialize the structural components of a __block variable, i.e.
1738/// everything but the actual object.
1739void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001740 // Find the address of the local.
1741 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001742
John McCallf0c11f72011-03-31 08:03:29 +00001743 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001744 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001745 cast<llvm::PointerType>(addr->getType())->getElementType());
1746
1747 // Build the byref helpers if necessary. This is null if we don't need any.
1748 CodeGenModule::ByrefHelpers *helpers =
1749 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001750
1751 const VarDecl &D = *emission.Variable;
1752 QualType type = D.getType();
1753
John McCallf0c11f72011-03-31 08:03:29 +00001754 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001755
1756 // Initialize the 'isa', which is just 0 or 1.
1757 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001758 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001759 isa = 1;
1760 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1761 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1762
1763 // Store the address of the variable into its own forwarding pointer.
1764 Builder.CreateStore(addr,
1765 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1766
1767 // Blocks ABI:
1768 // c) the flags field is set to either 0 if no helper functions are
1769 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1770 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001771 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001772 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1773 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1774
John McCallf0c11f72011-03-31 08:03:29 +00001775 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1776 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001777 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1778
John McCallf0c11f72011-03-31 08:03:29 +00001779 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001780 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001781 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001782
1783 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001784 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001785 }
1786}
1787
John McCalld16c2cf2011-02-08 08:22:06 +00001788void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001789 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001790 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001791 V = Builder.CreateBitCast(V, Int8PtrTy);
1792 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001793 Builder.CreateCall2(F, V, N);
1794}
John McCall5af02db2011-03-31 01:59:53 +00001795
1796namespace {
1797 struct CallBlockRelease : EHScopeStack::Cleanup {
1798 llvm::Value *Addr;
1799 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1800
John McCallad346f42011-07-12 20:27:29 +00001801 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001802 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001803 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1804 }
1805 };
1806}
1807
1808/// Enter a cleanup to destroy a __block variable. Note that this
1809/// cleanup should be a no-op if the variable hasn't left the stack
1810/// yet; if a cleanup is required for the variable itself, that needs
1811/// to be done externally.
1812void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1813 // We don't enter this cleanup if we're in pure-GC mode.
Douglas Gregore289d812011-09-13 17:21:33 +00001814 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001815 return;
1816
1817 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1818}
John McCall13db5cf2011-09-09 20:41:01 +00001819
1820/// Adjust the declaration of something from the blocks API.
1821static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1822 llvm::Constant *C) {
1823 if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1824
1825 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1826 if (GV->isDeclaration() &&
1827 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1828 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1829}
1830
1831llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1832 if (BlockObjectDispose)
1833 return BlockObjectDispose;
1834
1835 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1836 llvm::FunctionType *fty
1837 = llvm::FunctionType::get(VoidTy, args, false);
1838 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1839 configureBlocksRuntimeObject(*this, BlockObjectDispose);
1840 return BlockObjectDispose;
1841}
1842
1843llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1844 if (BlockObjectAssign)
1845 return BlockObjectAssign;
1846
1847 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1848 llvm::FunctionType *fty
1849 = llvm::FunctionType::get(VoidTy, args, false);
1850 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1851 configureBlocksRuntimeObject(*this, BlockObjectAssign);
1852 return BlockObjectAssign;
1853}
1854
1855llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1856 if (NSConcreteGlobalBlock)
1857 return NSConcreteGlobalBlock;
1858
1859 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
1860 Int8PtrTy->getPointerTo(), 0);
1861 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
1862 return NSConcreteGlobalBlock;
1863}
1864
1865llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
1866 if (NSConcreteStackBlock)
1867 return NSConcreteStackBlock;
1868
1869 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
1870 Int8PtrTy->getPointerTo(), 0);
1871 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
1872 return NSConcreteStackBlock;
1873}