blob: 09d3125ce81d0fad846312d9d2d9bd2b221bb6c6 [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 McCall1a343eb2011-11-10 08:15:53 +000028CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall6f103ba2011-11-10 10:43:54 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
31 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000032
John McCall1a343eb2011-11-10 08:15:53 +000033 // Skip asm prefix, if any. 'name' is usually taken directly from
34 // the mangled name of the enclosing function.
35 if (!name.empty() && name[0] == '\01')
36 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000037}
38
John McCallf0c11f72011-03-31 08:03:29 +000039// Anchor the vtable to this translation unit.
40CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
41
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the given block as a global block.
43static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo,
45 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000046
John McCall6b5a61b2011-02-07 10:33:21 +000047/// Build the helper function to copy a block.
48static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
49 const CGBlockInfo &blockInfo) {
50 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
51}
52
53/// Build the helper function to dipose of a block.
54static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
55 const CGBlockInfo &blockInfo) {
56 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
57}
58
59/// Build the block descriptor constant for a block.
60static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
61 const CGBlockInfo &blockInfo) {
62 ASTContext &C = CGM.getContext();
63
Chris Lattner2acc6e32011-07-18 04:24:23 +000064 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
65 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000066
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000068
69 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000070 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000071
72 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000073 // FIXME: What is the right way to say this doesn't fit? We should give
74 // a user diagnostic in that case. Better fix would be to change the
75 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000076 elements.push_back(llvm::ConstantInt::get(ulong,
77 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000078
John McCall6b5a61b2011-02-07 10:33:21 +000079 // Optional copy/dispose helpers.
80 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000081 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000082 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000083
84 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000085 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000086 }
87
John McCall6b5a61b2011-02-07 10:33:21 +000088 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
89 std::string typeAtEncoding =
90 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
91 elements.push_back(llvm::ConstantExpr::getBitCast(
92 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000093
John McCall6b5a61b2011-02-07 10:33:21 +000094 // GC layout.
David Blaikie4e4d0842012-03-11 07:00:24 +000095 if (C.getLangOpts().ObjC1)
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
97 else
98 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +000099
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000100 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000101
John McCall6b5a61b2011-02-07 10:33:21 +0000102 llvm::GlobalVariable *global =
103 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
104 llvm::GlobalValue::InternalLinkage,
105 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000108}
109
John McCall6b5a61b2011-02-07 10:33:21 +0000110/*
111 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
114 struct Block_literal {
115 /// Initialized to one of:
116 /// extern void *_NSConcreteStackBlock[];
117 /// extern void *_NSConcreteGlobalBlock[];
118 ///
119 /// In theory, we could start one off malloc'ed by setting
120 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
121 /// this isa:
122 /// extern void *_NSConcreteMallocBlock[];
123 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000124
John McCall6b5a61b2011-02-07 10:33:21 +0000125 /// These are the flags (with corresponding bit number) that the
126 /// compiler is actually supposed to know about.
127 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
128 /// descriptor provides copy and dispose helper functions
129 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
130 /// object with a nontrivial destructor or copy constructor
131 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
132 /// as global memory
133 /// 29. BLOCK_USE_STRET - indicates that the block function
134 /// uses stret, which objc_msgSend needs to know about
135 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
136 /// @encoded signature string
137 /// And we're not supposed to manipulate these:
138 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
139 /// to malloc'ed memory
140 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
141 /// to GC-allocated memory
142 /// Additionally, the bottom 16 bits are a reference count which
143 /// should be zero on the stack.
144 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000145
John McCall6b5a61b2011-02-07 10:33:21 +0000146 /// Reserved; should be zero-initialized.
147 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000148
John McCall6b5a61b2011-02-07 10:33:21 +0000149 /// Function pointer generated from block literal.
150 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
John McCall6b5a61b2011-02-07 10:33:21 +0000152 /// Block description metadata generated from block literal.
153 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000154
John McCall6b5a61b2011-02-07 10:33:21 +0000155 /// Captured values follow.
156 _CapturesTypes captures...;
157 };
158 */
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160/// The number of fields in a block header.
161const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163namespace {
164 /// A chunk of data that we actually have to capture in the block.
165 struct BlockLayoutChunk {
166 CharUnits Alignment;
167 CharUnits Size;
168 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000169 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171 BlockLayoutChunk(CharUnits align, CharUnits size,
172 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000173 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000174 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000175
John McCall6b5a61b2011-02-07 10:33:21 +0000176 /// Tell the block info that this chunk has the given field index.
177 void setIndex(CGBlockInfo &info, unsigned index) {
178 if (!Capture)
179 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000180 else
John McCall6b5a61b2011-02-07 10:33:21 +0000181 info.Captures[Capture->getVariable()]
182 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000183 }
John McCall6b5a61b2011-02-07 10:33:21 +0000184 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 /// Order by descending alignment.
187 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
188 return left.Alignment > right.Alignment;
189 }
190}
191
John McCall461c9c12011-02-08 03:07:00 +0000192/// Determines if the given type is safe for constant capture in C++.
193static bool isSafeForCXXConstantCapture(QualType type) {
194 const RecordType *recordType =
195 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
196
197 // Only records can be unsafe.
198 if (!recordType) return true;
199
200 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
201
202 // Maintain semantics for classes with non-trivial dtors or copy ctors.
203 if (!record->hasTrivialDestructor()) return false;
204 if (!record->hasTrivialCopyConstructor()) return false;
205
206 // Otherwise, we just have to make sure there aren't any mutable
207 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000208 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000209}
210
John McCall6b5a61b2011-02-07 10:33:21 +0000211/// It is illegal to modify a const object after initialization.
212/// Therefore, if a const object has a constant initializer, we don't
213/// actually need to keep storage for it in the block; we'll just
214/// rematerialize it at the start of the block function. This is
215/// acceptable because we make no promises about address stability of
216/// captured variables.
217static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000218 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000219 const VarDecl *var) {
220 QualType type = var->getType();
221
222 // We can only do this if the variable is const.
223 if (!type.isConstQualified()) return 0;
224
John McCall461c9c12011-02-08 03:07:00 +0000225 // Furthermore, in C++ we have to worry about mutable fields:
226 // C++ [dcl.type.cv]p4:
227 // Except that any class member declared mutable can be
228 // modified, any attempt to modify a const object during its
229 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000230 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000231 return 0;
232
233 // If the variable doesn't have any initializer (shouldn't this be
234 // invalid?), it's not clear what we should do. Maybe capture as
235 // zero?
236 const Expr *init = var->getInit();
237 if (!init) return 0;
238
Richard Smith2d6a5672012-01-14 04:30:29 +0000239 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000240}
241
242/// Get the low bit of a nonzero character count. This is the
243/// alignment of the nth byte if the 0th byte is universally aligned.
244static CharUnits getLowBit(CharUnits v) {
245 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
246}
247
248static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000250 ASTContext &C = CGM.getContext();
251
252 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
253 CharUnits ptrSize, ptrAlign, intSize, intAlign;
254 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
255 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
256
257 // Are there crazy embedded platforms where this isn't true?
258 assert(intSize <= ptrSize && "layout assumptions horribly violated");
259
260 CharUnits headerSize = ptrSize;
261 if (2 * intSize < ptrAlign) headerSize += ptrSize;
262 else headerSize += 2 * intSize;
263 headerSize += 2 * ptrSize;
264
265 info.BlockAlign = ptrAlign;
266 info.BlockSize = headerSize;
267
268 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000269 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
270 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000271 elementTypes.push_back(i8p);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(intTy);
274 elementTypes.push_back(i8p);
275 elementTypes.push_back(CGM.getBlockDescriptorType());
276
277 assert(elementTypes.size() == BlockHeaderSize);
278}
279
280/// Compute the layout of the given block. Attempts to lay the block
281/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000282static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
283 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000284 ASTContext &C = CGM.getContext();
285 const BlockDecl *block = info.getBlockDecl();
286
Chris Lattner5f9e2722011-07-23 10:55:15 +0000287 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000288 initializeForBlockHeader(CGM, info, elementTypes);
289
290 if (!block->hasCaptures()) {
291 info.StructureType =
292 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
293 info.CanBeGlobal = true;
294 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000295 }
Mike Stump00470a12009-03-05 08:32:30 +0000296
John McCall6b5a61b2011-02-07 10:33:21 +0000297 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000299 layout.reserve(block->capturesCXXThis() +
300 (block->capture_end() - block->capture_begin()));
301
302 CharUnits maxFieldAlign;
303
304 // First, 'this'.
305 if (block->capturesCXXThis()) {
306 const DeclContext *DC = block->getDeclContext();
307 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
308 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000309 QualType thisType;
310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
311 thisType = C.getPointerType(C.getRecordType(RD));
312 else
313 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000314
Jay Foadef6de3d2011-07-11 09:56:20 +0000315 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000316 std::pair<CharUnits,CharUnits> tinfo
317 = CGM.getContext().getTypeInfoInChars(thisType);
318 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
319
320 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
321 }
322
323 // Next, all the block captures.
324 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
325 ce = block->capture_end(); ci != ce; ++ci) {
326 const VarDecl *variable = ci->getVariable();
327
328 if (ci->isByRef()) {
329 // We have to copy/dispose of the __block reference.
330 info.NeedsCopyDispose = true;
331
John McCall6b5a61b2011-02-07 10:33:21 +0000332 // Just use void* instead of a pointer to the byref type.
333 QualType byRefPtrTy = C.VoidPtrTy;
334
Jay Foadef6de3d2011-07-11 09:56:20 +0000335 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000336 std::pair<CharUnits,CharUnits> tinfo
337 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
338 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339
340 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
341 &*ci, llvmType));
342 continue;
343 }
344
345 // Otherwise, build a layout chunk with the size and alignment of
346 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000347 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000348 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
349 continue;
350 }
351
John McCallf85e1932011-06-15 23:02:42 +0000352 // If we have a lifetime qualifier, honor it for capture purposes.
353 // That includes *not* copying it if it's __unsafe_unretained.
354 if (Qualifiers::ObjCLifetime lifetime
355 = variable->getType().getObjCLifetime()) {
356 switch (lifetime) {
357 case Qualifiers::OCL_None: llvm_unreachable("impossible");
358 case Qualifiers::OCL_ExplicitNone:
359 case Qualifiers::OCL_Autoreleasing:
360 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000361
John McCallf85e1932011-06-15 23:02:42 +0000362 case Qualifiers::OCL_Strong:
363 case Qualifiers::OCL_Weak:
364 info.NeedsCopyDispose = true;
365 }
366
367 // Block pointers require copy/dispose. So do Objective-C pointers.
368 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000369 info.NeedsCopyDispose = true;
370
371 // So do types that require non-trivial copy construction.
372 } else if (ci->hasCopyExpr()) {
373 info.NeedsCopyDispose = true;
374 info.HasCXXObject = true;
375
376 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000377 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000378 if (const CXXRecordDecl *record =
379 variable->getType()->getAsCXXRecordDecl()) {
380 if (!record->hasTrivialDestructor()) {
381 info.HasCXXObject = true;
382 info.NeedsCopyDispose = true;
383 }
384 }
385 }
386
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000387 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000388 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000389 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000390
John McCall6b5a61b2011-02-07 10:33:21 +0000391 maxFieldAlign = std::max(maxFieldAlign, align);
392
Jay Foadef6de3d2011-07-11 09:56:20 +0000393 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000394 CGM.getTypes().ConvertTypeForMem(VT);
395
John McCall6b5a61b2011-02-07 10:33:21 +0000396 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
397 }
398
399 // If that was everything, we're done here.
400 if (layout.empty()) {
401 info.StructureType =
402 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
403 info.CanBeGlobal = true;
404 return;
405 }
406
407 // Sort the layout by alignment. We have to use a stable sort here
408 // to get reproducible results. There should probably be an
409 // llvm::array_pod_stable_sort.
410 std::stable_sort(layout.begin(), layout.end());
411
412 CharUnits &blockSize = info.BlockSize;
413 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
414
415 // Assuming that the first byte in the header is maximally aligned,
416 // get the alignment of the first byte following the header.
417 CharUnits endAlign = getLowBit(blockSize);
418
419 // If the end of the header isn't satisfactorily aligned for the
420 // maximum thing, look for things that are okay with the header-end
421 // alignment, and keep appending them until we get something that's
422 // aligned right. This algorithm is only guaranteed optimal if
423 // that condition is satisfied at some point; otherwise we can get
424 // things like:
425 // header // next byte has alignment 4
426 // something_with_size_5; // next byte has alignment 1
427 // something_with_alignment_8;
428 // which has 7 bytes of padding, as opposed to the naive solution
429 // which might have less (?).
430 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000431 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000432 li = layout.begin() + 1, le = layout.end();
433
434 // Look for something that the header end is already
435 // satisfactorily aligned for.
436 for (; li != le && endAlign < li->Alignment; ++li)
437 ;
438
439 // If we found something that's naturally aligned for the end of
440 // the header, keep adding things...
441 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000442 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000443 for (; li != le; ++li) {
444 assert(endAlign >= li->Alignment);
445
446 li->setIndex(info, elementTypes.size());
447 elementTypes.push_back(li->Type);
448 blockSize += li->Size;
449 endAlign = getLowBit(blockSize);
450
451 // ...until we get to the alignment of the maximum field.
452 if (endAlign >= maxFieldAlign)
453 break;
454 }
455
456 // Don't re-append everything we just appended.
457 layout.erase(first, li);
458 }
459 }
460
461 // At this point, we just have to add padding if the end align still
462 // isn't aligned right.
463 if (endAlign < maxFieldAlign) {
464 CharUnits padding = maxFieldAlign - endAlign;
465
John McCall5936e332011-02-15 09:22:45 +0000466 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
467 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000468 blockSize += padding;
469
470 endAlign = getLowBit(blockSize);
471 assert(endAlign >= maxFieldAlign);
472 }
473
474 // Slam everything else on now. This works because they have
475 // strictly decreasing alignment and we expect that size is always a
476 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000477 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000478 li = layout.begin(), le = layout.end(); li != le; ++li) {
479 assert(endAlign >= li->Alignment);
480 li->setIndex(info, elementTypes.size());
481 elementTypes.push_back(li->Type);
482 blockSize += li->Size;
483 endAlign = getLowBit(blockSize);
484 }
485
486 info.StructureType =
487 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
488}
489
John McCall1a343eb2011-11-10 08:15:53 +0000490/// Enter the scope of a block. This should be run at the entrance to
491/// a full-expression so that the block's cleanups are pushed at the
492/// right place in the stack.
493static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
494 // Allocate the block info and place it at the head of the list.
495 CGBlockInfo &blockInfo =
496 *new CGBlockInfo(block, CGF.CurFn->getName());
497 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
498 CGF.FirstBlockInfo = &blockInfo;
499
500 // Compute information about the layout, etc., of this block,
501 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000502 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000503
504 // Nothing else to do if it can be global.
505 if (blockInfo.CanBeGlobal) return;
506
507 // Make the allocation for the block.
508 blockInfo.Address =
509 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
510 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
511
512 // If there are cleanups to emit, enter them (but inactive).
513 if (!blockInfo.NeedsCopyDispose) return;
514
515 // Walk through the captures (in order) and find the ones not
516 // captured by constant.
517 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
518 ce = block->capture_end(); ci != ce; ++ci) {
519 // Ignore __block captures; there's nothing special in the
520 // on-stack block that we need to do for them.
521 if (ci->isByRef()) continue;
522
523 // Ignore variables that are constant-captured.
524 const VarDecl *variable = ci->getVariable();
525 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
526 if (capture.isConstant()) continue;
527
528 // Ignore objects that aren't destructed.
529 QualType::DestructionKind dtorKind =
530 variable->getType().isDestructedType();
531 if (dtorKind == QualType::DK_none) continue;
532
533 CodeGenFunction::Destroyer *destroyer;
534
535 // Block captures count as local values and have imprecise semantics.
536 // They also can't be arrays, so need to worry about that.
537 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000538 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000539 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000540 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000541 }
542
543 // GEP down to the address.
544 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
545 capture.getIndex());
546
John McCall6f103ba2011-11-10 10:43:54 +0000547 // We can use that GEP as the dominating IP.
548 if (!blockInfo.DominatingIP)
549 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
550
John McCall1a343eb2011-11-10 08:15:53 +0000551 CleanupKind cleanupKind = InactiveNormalCleanup;
552 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
553 if (useArrayEHCleanup)
554 cleanupKind = InactiveNormalAndEHCleanup;
555
556 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000557 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000558
559 // Remember where that cleanup was.
560 capture.setCleanup(CGF.EHStack.stable_begin());
561 }
562}
563
564/// Enter a full-expression with a non-trivial number of objects to
565/// clean up. This is in this file because, at the moment, the only
566/// kind of cleanup object is a BlockDecl*.
567void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
568 assert(E->getNumObjects() != 0);
569 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
570 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
571 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
572 enterBlockScope(*this, *i);
573 }
574}
575
576/// Find the layout for the given block in a linked list and remove it.
577static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
578 const BlockDecl *block) {
579 while (true) {
580 assert(head && *head);
581 CGBlockInfo *cur = *head;
582
583 // If this is the block we're looking for, splice it out of the list.
584 if (cur->getBlockDecl() == block) {
585 *head = cur->NextBlockInfo;
586 return cur;
587 }
588
589 head = &cur->NextBlockInfo;
590 }
591}
592
593/// Destroy a chain of block layouts.
594void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
595 assert(head && "destroying an empty chain");
596 do {
597 CGBlockInfo *cur = head;
598 head = cur->NextBlockInfo;
599 delete cur;
600 } while (head != 0);
601}
602
John McCall6b5a61b2011-02-07 10:33:21 +0000603/// Emit a block literal expression in the current function.
604llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000605 // If the block has no captures, we won't have a pre-computed
606 // layout for it.
607 if (!blockExpr->getBlockDecl()->hasCaptures()) {
608 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000609 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000610 blockInfo.BlockExpression = blockExpr;
611 return EmitBlockLiteral(blockInfo);
612 }
John McCall6b5a61b2011-02-07 10:33:21 +0000613
John McCall1a343eb2011-11-10 08:15:53 +0000614 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000615 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000616 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
617 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000618
John McCall1a343eb2011-11-10 08:15:53 +0000619 blockInfo->BlockExpression = blockExpr;
620 return EmitBlockLiteral(*blockInfo);
621}
622
623llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
624 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000625 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000626 llvm::Constant *blockFn
627 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000628 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000629 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000630 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000631
632 // If there is nothing to capture, we can emit this as a global block.
633 if (blockInfo.CanBeGlobal)
634 return buildGlobalBlock(CGM, blockInfo, blockFn);
635
636 // Otherwise, we have to emit this as a local block.
637
638 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000639 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000640
641 // Build the block descriptor.
642 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
643
John McCall1a343eb2011-11-10 08:15:53 +0000644 llvm::AllocaInst *blockAddr = blockInfo.Address;
645 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000646
647 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000648 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000649 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
650 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000651 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000652
653 // Initialize the block literal.
654 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000655 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000656 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000657 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000658 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
659 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
660 "block.invoke"));
661 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
662 "block.descriptor"));
663
664 // Finally, capture all the values into the block.
665 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
666
667 // First, 'this'.
668 if (blockDecl->capturesCXXThis()) {
669 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
670 blockInfo.CXXThisIndex,
671 "block.captured-this.addr");
672 Builder.CreateStore(LoadCXXThis(), addr);
673 }
674
675 // Next, captured variables.
676 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
677 ce = blockDecl->capture_end(); ci != ce; ++ci) {
678 const VarDecl *variable = ci->getVariable();
679 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
680
681 // Ignore constant captures.
682 if (capture.isConstant()) continue;
683
684 QualType type = variable->getType();
685
686 // This will be a [[type]]*, except that a byref entry will just be
687 // an i8**.
688 llvm::Value *blockField =
689 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
690 "block.captured");
691
692 // Compute the address of the thing we're going to move into the
693 // block literal.
694 llvm::Value *src;
695 if (ci->isNested()) {
696 // We need to use the capture from the enclosing block.
697 const CGBlockInfo::Capture &enclosingCapture =
698 BlockInfo->getCapture(variable);
699
700 // This is a [[type]]*, except that a byref entry wil just be an i8**.
701 src = Builder.CreateStructGEP(LoadBlockStruct(),
702 enclosingCapture.getIndex(),
703 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000704 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000705 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000706 // special; we'll simply emit it directly.
707 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000708 } else {
709 // This is a [[type]]*.
710 src = LocalDeclMap[variable];
711 }
712
713 // For byrefs, we just write the pointer to the byref struct into
714 // the block field. There's no need to chase the forwarding
715 // pointer at this point, since we're building something that will
716 // live a shorter life than the stack byref anyway.
717 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000718 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000719 if (ci->isNested())
720 src = Builder.CreateLoad(src, "byref.capture");
721 else
John McCall5936e332011-02-15 09:22:45 +0000722 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000723
John McCall5936e332011-02-15 09:22:45 +0000724 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000725 Builder.CreateStore(src, blockField);
726
727 // If we have a copy constructor, evaluate that into the block field.
728 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000729 if (blockDecl->isConversionFromLambda()) {
730 // If we have a lambda conversion, emit the expression
731 // directly into the block instead.
732 CharUnits Align = getContext().getTypeAlignInChars(type);
733 AggValueSlot Slot =
734 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
735 AggValueSlot::IsDestructed,
736 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000737 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000738 EmitAggExpr(copyExpr, Slot);
739 } else {
740 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
741 }
John McCall6b5a61b2011-02-07 10:33:21 +0000742
743 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000744 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000745 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
746
747 // Otherwise, fake up a POD copy into the block field.
748 } else {
John McCallf85e1932011-06-15 23:02:42 +0000749 // Fake up a new variable so that EmitScalarInit doesn't think
750 // we're referring to the variable in its own initializer.
751 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000752 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000753
John McCallbb699b02011-02-07 18:37:40 +0000754 // We use one of these or the other depending on whether the
755 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000756 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
757 /*refersToEnclosing*/ ci->isNested(), type,
758 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000759
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000760 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000761 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000762 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000763 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000764 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000765 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000766 }
767
John McCall1a343eb2011-11-10 08:15:53 +0000768 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000769 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000770 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
771 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000772 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000773 }
John McCall6b5a61b2011-02-07 10:33:21 +0000774 }
775
776 // Cast to the converted block-pointer type, which happens (somewhat
777 // unfortunately) to be a pointer to function type.
778 llvm::Value *result =
779 Builder.CreateBitCast(blockAddr,
780 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000781
John McCall6b5a61b2011-02-07 10:33:21 +0000782 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000783}
784
785
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000786llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000787 if (BlockDescriptorType)
788 return BlockDescriptorType;
789
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000790 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000791 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000792
Mike Stumpab695142009-02-13 15:16:56 +0000793 // struct __block_descriptor {
794 // unsigned long reserved;
795 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000796 //
797 // // later, the following will be added
798 //
799 // struct {
800 // void (*copyHelper)();
801 // void (*copyHelper)();
802 // } helpers; // !!! optional
803 //
804 // const char *signature; // the block signature
805 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000806 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000807 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000808 llvm::StructType::create("struct.__block_descriptor",
809 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000810
John McCall6b5a61b2011-02-07 10:33:21 +0000811 // Now form a pointer to that.
812 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000813 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000814}
815
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000816llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000817 if (GenericBlockLiteralType)
818 return GenericBlockLiteralType;
819
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000820 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000821
Mike Stump9b8a7972009-02-13 15:25:34 +0000822 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000823 // void *__isa;
824 // int __flags;
825 // int __reserved;
826 // void (*__invoke)(void *);
827 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000828 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000829 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000830 llvm::StructType::create("struct.__block_literal_generic",
831 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
832 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000833
Mike Stump9b8a7972009-02-13 15:25:34 +0000834 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000835}
836
Mike Stumpbd65cac2009-02-19 01:01:04 +0000837
Anders Carlssona1736c02009-12-24 21:13:40 +0000838RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
839 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000840 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000841 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000842
Anders Carlssonacfde802009-02-12 00:39:25 +0000843 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
844
845 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000846 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000847 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000848
849 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000850 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000851 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
852
853 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000854 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000855
Benjamin Kramer578faa82011-09-27 21:06:10 +0000856 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000857
Anders Carlssonacfde802009-02-12 00:39:25 +0000858 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000859 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000860 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000861
Anders Carlsson782f3972009-04-08 23:13:16 +0000862 QualType FnType = BPT->getPointeeType();
863
Anders Carlssonacfde802009-02-12 00:39:25 +0000864 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000865 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000866 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000867
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000868 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000869 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000870
John McCall64cd2322011-03-09 08:39:33 +0000871 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000872 const CGFunctionInfo &FnInfo =
873 CGM.getTypes().arrangeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000875 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000876 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Chris Lattner2acc6e32011-07-18 04:24:23 +0000878 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000879 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Anders Carlssonacfde802009-02-12 00:39:25 +0000881 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000882 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000883}
Anders Carlssond5cab542009-02-12 17:55:02 +0000884
John McCall6b5a61b2011-02-07 10:33:21 +0000885llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
886 bool isByRef) {
887 assert(BlockInfo && "evaluating block ref without block information?");
888 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000889
John McCall6b5a61b2011-02-07 10:33:21 +0000890 // Handle constant captures.
891 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000892
John McCall6b5a61b2011-02-07 10:33:21 +0000893 llvm::Value *addr =
894 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
895 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000896
John McCall6b5a61b2011-02-07 10:33:21 +0000897 if (isByRef) {
898 // addr should be a void** right now. Load, then cast the result
899 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000900
John McCall6b5a61b2011-02-07 10:33:21 +0000901 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000902 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000903 = llvm::PointerType::get(BuildByRefType(variable), 0);
904 addr = Builder.CreateBitCast(addr, byrefPointerType,
905 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 // Follow the forwarding pointer.
908 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
909 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911 // Cast back to byref* and GEP over to the actual object.
912 addr = Builder.CreateBitCast(addr, byrefPointerType);
913 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
914 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000915 }
916
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000917 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000918 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000919
John McCall6b5a61b2011-02-07 10:33:21 +0000920 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000921}
922
Mike Stump67a64482009-02-14 22:16:35 +0000923llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000924CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000925 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000926 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
927 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000928
John McCall6b5a61b2011-02-07 10:33:21 +0000929 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000930 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000931
John McCall6b5a61b2011-02-07 10:33:21 +0000932 // Using that metadata, generate the actual block function.
933 llvm::Constant *blockFn;
934 {
935 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000936 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
937 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000938 0, LocalDeclMap,
939 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000940 }
John McCall5936e332011-02-15 09:22:45 +0000941 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000942
John McCalld16c2cf2011-02-08 08:22:06 +0000943 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000944}
945
John McCall6b5a61b2011-02-07 10:33:21 +0000946static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
947 const CGBlockInfo &blockInfo,
948 llvm::Constant *blockFn) {
949 assert(blockInfo.CanBeGlobal);
950
951 // Generate the constants for the block literal initializer.
952 llvm::Constant *fields[BlockHeaderSize];
953
954 // isa
955 fields[0] = CGM.getNSConcreteGlobalBlock();
956
957 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000958 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
959 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
960
John McCall5936e332011-02-15 09:22:45 +0000961 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000962
963 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000964 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000965
966 // Function
967 fields[3] = blockFn;
968
969 // Descriptor
970 fields[4] = buildBlockDescriptor(CGM, blockInfo);
971
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000972 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000973
974 llvm::GlobalVariable *literal =
975 new llvm::GlobalVariable(CGM.getModule(),
976 init->getType(),
977 /*constant*/ true,
978 llvm::GlobalVariable::InternalLinkage,
979 init,
980 "__block_literal_global");
981 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
982
983 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000984 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000985 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
986 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000987}
988
Mike Stump00470a12009-03-05 08:32:30 +0000989llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000990CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
991 const CGBlockInfo &blockInfo,
992 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +0000993 const DeclMapTy &ldm,
994 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +0000995 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000996
Devang Patel6d1155b2011-03-07 21:53:18 +0000997 // Check if we should generate debug info for this block function.
998 if (CGM.getModuleDebugInfo())
999 DebugInfo = CGM.getModuleDebugInfo();
1000
John McCall6b5a61b2011-02-07 10:33:21 +00001001 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Mike Stump7f28a9c2009-03-13 23:34:28 +00001003 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001004 // to be local to this function as well, in case they're directly
1005 // referenced in a block.
1006 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1007 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1008 if (var && !var->hasLocalStorage())
1009 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001010 }
1011
John McCall6b5a61b2011-02-07 10:33:21 +00001012 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001013
John McCall6b5a61b2011-02-07 10:33:21 +00001014 // Build the argument list.
1015 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001016
John McCall6b5a61b2011-02-07 10:33:21 +00001017 // The first argument is the block pointer. Just take it as a void*
1018 // and cast it later.
1019 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001020 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001021
John McCall8178df32011-02-22 22:38:33 +00001022 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1023 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001024 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001025
John McCall6b5a61b2011-02-07 10:33:21 +00001026 // Now add the rest of the parameters.
1027 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1028 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001029 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001030
John McCall6b5a61b2011-02-07 10:33:21 +00001031 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001032 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001033 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001034 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1035 fnType->getExtInfo(),
1036 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001037 if (CGM.ReturnTypeUsesSRet(fnInfo))
1038 blockInfo.UsesStret = true;
1039
John McCallde5d3c72012-02-17 03:33:10 +00001040 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001041
John McCall6b5a61b2011-02-07 10:33:21 +00001042 MangleBuffer name;
1043 CGM.getBlockMangledName(GD, name, blockDecl);
1044 llvm::Function *fn =
1045 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1046 name.getString(), &CGM.getModule());
1047 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001048
John McCall6b5a61b2011-02-07 10:33:21 +00001049 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001050 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001051 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001052 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001053
John McCall8178df32011-02-22 22:38:33 +00001054 // Okay. Undo some of what StartFunction did.
1055
1056 // Pull the 'self' reference out of the local decl map.
1057 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1058 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001059 BlockPointer = Builder.CreateBitCast(blockAddr,
1060 blockInfo.StructureType->getPointerTo(),
1061 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001062
John McCallea1471e2010-05-20 01:18:31 +00001063 // If we have a C++ 'this' reference, go ahead and force it into
1064 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001065 if (blockDecl->capturesCXXThis()) {
1066 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1067 blockInfo.CXXThisIndex,
1068 "block.captured-this");
1069 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001070 }
1071
John McCall6b5a61b2011-02-07 10:33:21 +00001072 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1073 // appease it.
1074 if (const ObjCMethodDecl *method
1075 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1076 const VarDecl *self = method->getSelfDecl();
1077
1078 // There might not be a capture for 'self', but if there is...
1079 if (blockInfo.Captures.count(self)) {
1080 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1081 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1082 capture.getIndex(),
1083 "block.captured-self");
1084 LocalDeclMap[self] = selfAddr;
1085 }
1086 }
1087
1088 // Also force all the constant captures.
1089 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1090 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1091 const VarDecl *variable = ci->getVariable();
1092 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1093 if (!capture.isConstant()) continue;
1094
1095 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1096
1097 llvm::AllocaInst *alloca =
1098 CreateMemTemp(variable->getType(), "block.captured-const");
1099 alloca->setAlignment(align);
1100
1101 Builder.CreateStore(capture.getConstant(), alloca, align);
1102
1103 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001104 }
1105
John McCallf4b88a42012-03-10 09:33:50 +00001106 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001107 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1108 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1109 --entry_ptr;
1110
Eli Friedman64bee652012-02-25 02:48:22 +00001111 if (IsLambdaConversionToBlock)
1112 EmitLambdaBlockInvokeBody();
1113 else
1114 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001115
Mike Stumpde8c5c72009-10-01 00:27:30 +00001116 // Remember where we were...
1117 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001118
Mike Stumpde8c5c72009-10-01 00:27:30 +00001119 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001120 ++entry_ptr;
1121 Builder.SetInsertPoint(entry, entry_ptr);
1122
John McCallf4b88a42012-03-10 09:33:50 +00001123 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001124 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001125 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001126 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1127 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1128 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001129 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001130
1131 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1132 if (capture.isConstant()) {
1133 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1134 Builder);
1135 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001136 }
John McCall6b5a61b2011-02-07 10:33:21 +00001137
John McCall8178df32011-02-22 22:38:33 +00001138 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001139 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001140 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001141 }
John McCall6b5a61b2011-02-07 10:33:21 +00001142
Mike Stumpde8c5c72009-10-01 00:27:30 +00001143 // And resume where we left off.
1144 if (resume == 0)
1145 Builder.ClearInsertionPoint();
1146 else
1147 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001148
John McCall6b5a61b2011-02-07 10:33:21 +00001149 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001150
John McCall6b5a61b2011-02-07 10:33:21 +00001151 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001152}
Mike Stumpa99038c2009-02-28 09:07:16 +00001153
John McCall6b5a61b2011-02-07 10:33:21 +00001154/*
1155 notes.push_back(HelperInfo());
1156 HelperInfo &note = notes.back();
1157 note.index = capture.getIndex();
1158 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1159 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001160
John McCall6b5a61b2011-02-07 10:33:21 +00001161 if (ci->isByRef()) {
1162 note.flag = BLOCK_FIELD_IS_BYREF;
1163 if (type.isObjCGCWeak())
1164 note.flag |= BLOCK_FIELD_IS_WEAK;
1165 } else if (type->isBlockPointerType()) {
1166 note.flag = BLOCK_FIELD_IS_BLOCK;
1167 } else {
1168 note.flag = BLOCK_FIELD_IS_OBJECT;
1169 }
1170 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001171
Mike Stump00470a12009-03-05 08:32:30 +00001172
Mike Stumpa99038c2009-02-28 09:07:16 +00001173
John McCall6b5a61b2011-02-07 10:33:21 +00001174llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001175CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001176 ASTContext &C = getContext();
1177
1178 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001179 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1180 args.push_back(&dstDecl);
1181 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1182 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Mike Stumpa4f668f2009-03-06 01:33:24 +00001184 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001185 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1186 FunctionType::ExtInfo(),
1187 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001188
John McCall6b5a61b2011-02-07 10:33:21 +00001189 // FIXME: it would be nice if these were mergeable with things with
1190 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001191 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001192
1193 llvm::Function *Fn =
1194 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001195 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001196
1197 IdentifierInfo *II
1198 = &CGM.getContext().Idents.get("__copy_helper_block_");
1199
Devang Patel58dc5ca2011-05-02 20:37:08 +00001200 // Check if we should generate debug info for this block helper function.
1201 if (CGM.getModuleDebugInfo())
1202 DebugInfo = CGM.getModuleDebugInfo();
1203
John McCall6b5a61b2011-02-07 10:33:21 +00001204 FunctionDecl *FD = FunctionDecl::Create(C,
1205 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001206 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001207 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001208 SC_Static,
1209 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001210 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001211 true);
John McCalld26bc762011-03-09 04:27:21 +00001212 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001213
Chris Lattner2acc6e32011-07-18 04:24:23 +00001214 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001215
John McCalld26bc762011-03-09 04:27:21 +00001216 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001217 src = Builder.CreateLoad(src);
1218 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001219
John McCalld26bc762011-03-09 04:27:21 +00001220 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001221 dst = Builder.CreateLoad(dst);
1222 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001223
John McCall6b5a61b2011-02-07 10:33:21 +00001224 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001225
John McCall6b5a61b2011-02-07 10:33:21 +00001226 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1227 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1228 const VarDecl *variable = ci->getVariable();
1229 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001230
John McCall6b5a61b2011-02-07 10:33:21 +00001231 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1232 if (capture.isConstant()) continue;
1233
1234 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001235 BlockFieldFlags flags;
1236
1237 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001238
1239 if (copyExpr) {
1240 assert(!ci->isByRef());
1241 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001242
John McCall6b5a61b2011-02-07 10:33:21 +00001243 } else if (ci->isByRef()) {
1244 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001245 if (type.isObjCGCWeak())
1246 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001247
John McCallf85e1932011-06-15 23:02:42 +00001248 } else if (type->isObjCRetainableType()) {
1249 flags = BLOCK_FIELD_IS_OBJECT;
1250 if (type->isBlockPointerType())
1251 flags = BLOCK_FIELD_IS_BLOCK;
1252
1253 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001254 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001255 Qualifiers qs = type.getQualifiers();
1256
1257 // Don't generate special copy logic for a captured object
1258 // unless it's __strong or __weak.
1259 if (!qs.hasStrongOrWeakObjCLifetime())
1260 continue;
1261
1262 // Support __weak direct captures.
1263 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1264 isARCWeakCapture = true;
1265 }
1266 } else {
1267 continue;
1268 }
John McCall6b5a61b2011-02-07 10:33:21 +00001269
1270 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001271 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1272 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001273
1274 // If there's an explicit copy expression, we do that.
1275 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001276 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001277 } else if (isARCWeakCapture) {
1278 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001279 } else {
1280 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001281 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1282 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001283 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001284 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001285 }
1286 }
1287
John McCalld16c2cf2011-02-08 08:22:06 +00001288 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001289
John McCall5936e332011-02-15 09:22:45 +00001290 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001291}
1292
John McCall6b5a61b2011-02-07 10:33:21 +00001293llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001294CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001295 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001296
John McCall6b5a61b2011-02-07 10:33:21 +00001297 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001298 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1299 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Mike Stumpa4f668f2009-03-06 01:33:24 +00001301 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001302 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1303 FunctionType::ExtInfo(),
1304 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001305
Mike Stump3899a7f2009-06-05 23:26:36 +00001306 // FIXME: We'd like to put these into a mergable by content, with
1307 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001308 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001309
1310 llvm::Function *Fn =
1311 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001312 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001313
Devang Patel58dc5ca2011-05-02 20:37:08 +00001314 // Check if we should generate debug info for this block destroy function.
1315 if (CGM.getModuleDebugInfo())
1316 DebugInfo = CGM.getModuleDebugInfo();
1317
Mike Stumpa4f668f2009-03-06 01:33:24 +00001318 IdentifierInfo *II
1319 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1320
John McCall6b5a61b2011-02-07 10:33:21 +00001321 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001322 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001323 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001324 SC_Static,
1325 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001326 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001327 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001328
Chris Lattner2acc6e32011-07-18 04:24:23 +00001329 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001330
John McCalld26bc762011-03-09 04:27:21 +00001331 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001332 src = Builder.CreateLoad(src);
1333 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001334
John McCall6b5a61b2011-02-07 10:33:21 +00001335 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1336
John McCalld16c2cf2011-02-08 08:22:06 +00001337 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001338
1339 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1340 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1341 const VarDecl *variable = ci->getVariable();
1342 QualType type = variable->getType();
1343
1344 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1345 if (capture.isConstant()) continue;
1346
John McCalld16c2cf2011-02-08 08:22:06 +00001347 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001348 const CXXDestructorDecl *dtor = 0;
1349
John McCallf85e1932011-06-15 23:02:42 +00001350 bool isARCWeakCapture = false;
1351
John McCall6b5a61b2011-02-07 10:33:21 +00001352 if (ci->isByRef()) {
1353 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001354 if (type.isObjCGCWeak())
1355 flags |= BLOCK_FIELD_IS_WEAK;
1356 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1357 if (record->hasTrivialDestructor())
1358 continue;
1359 dtor = record->getDestructor();
1360 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001361 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001362 if (type->isBlockPointerType())
1363 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001364
John McCallf85e1932011-06-15 23:02:42 +00001365 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001366 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001367 Qualifiers qs = type.getQualifiers();
1368
1369 // Don't generate special dispose logic for a captured object
1370 // unless it's __strong or __weak.
1371 if (!qs.hasStrongOrWeakObjCLifetime())
1372 continue;
1373
1374 // Support __weak direct captures.
1375 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1376 isARCWeakCapture = true;
1377 }
1378 } else {
1379 continue;
1380 }
John McCall6b5a61b2011-02-07 10:33:21 +00001381
1382 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001383 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001384
1385 // If there's an explicit copy expression, we do that.
1386 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001387 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001388
John McCallf85e1932011-06-15 23:02:42 +00001389 // If this is a __weak capture, emit the release directly.
1390 } else if (isARCWeakCapture) {
1391 EmitARCDestroyWeak(srcField);
1392
John McCall6b5a61b2011-02-07 10:33:21 +00001393 // Otherwise we call _Block_object_dispose. It wouldn't be too
1394 // hard to just emit this as a cleanup if we wanted to make sure
1395 // that things were done in reverse.
1396 } else {
1397 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001398 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001399 BuildBlockRelease(value, flags);
1400 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001401 }
1402
John McCall6b5a61b2011-02-07 10:33:21 +00001403 cleanups.ForceCleanup();
1404
John McCalld16c2cf2011-02-08 08:22:06 +00001405 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001406
John McCall5936e332011-02-15 09:22:45 +00001407 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001408}
1409
John McCallf0c11f72011-03-31 08:03:29 +00001410namespace {
1411
1412/// Emits the copy/dispose helper functions for a __block object of id type.
1413class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1414 BlockFieldFlags Flags;
1415
1416public:
1417 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1418 : ByrefHelpers(alignment), Flags(flags) {}
1419
John McCall36170192011-03-31 09:19:20 +00001420 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1421 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001422 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1423
1424 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1425 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1426
1427 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1428
1429 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1430 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1431 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1432 }
1433
1434 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1435 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1436 llvm::Value *value = CGF.Builder.CreateLoad(field);
1437
1438 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1439 }
1440
1441 void profileImpl(llvm::FoldingSetNodeID &id) const {
1442 id.AddInteger(Flags.getBitMask());
1443 }
1444};
1445
John McCallf85e1932011-06-15 23:02:42 +00001446/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1447class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1448public:
1449 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1450
1451 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1452 llvm::Value *srcField) {
1453 CGF.EmitARCMoveWeak(destField, srcField);
1454 }
1455
1456 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1457 CGF.EmitARCDestroyWeak(field);
1458 }
1459
1460 void profileImpl(llvm::FoldingSetNodeID &id) const {
1461 // 0 is distinguishable from all pointers and byref flags
1462 id.AddInteger(0);
1463 }
1464};
1465
1466/// Emits the copy/dispose helpers for an ARC __block __strong variable
1467/// that's not of block-pointer type.
1468class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1469public:
1470 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1471
1472 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1473 llvm::Value *srcField) {
1474 // Do a "move" by copying the value and then zeroing out the old
1475 // variable.
1476
John McCalla59e4b72011-11-09 03:17:26 +00001477 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1478 value->setAlignment(Alignment.getQuantity());
1479
John McCallf85e1932011-06-15 23:02:42 +00001480 llvm::Value *null =
1481 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001482
1483 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1484 store->setAlignment(Alignment.getQuantity());
1485
1486 store = CGF.Builder.CreateStore(null, srcField);
1487 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001488 }
1489
1490 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCalla59e4b72011-11-09 03:17:26 +00001491 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1492 value->setAlignment(Alignment.getQuantity());
1493
John McCallf85e1932011-06-15 23:02:42 +00001494 CGF.EmitARCRelease(value, /*precise*/ false);
1495 }
1496
1497 void profileImpl(llvm::FoldingSetNodeID &id) const {
1498 // 1 is distinguishable from all pointers and byref flags
1499 id.AddInteger(1);
1500 }
1501};
1502
John McCalla59e4b72011-11-09 03:17:26 +00001503/// Emits the copy/dispose helpers for an ARC __block __strong
1504/// variable that's of block-pointer type.
1505class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1506public:
1507 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1508
1509 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1510 llvm::Value *srcField) {
1511 // Do the copy with objc_retainBlock; that's all that
1512 // _Block_object_assign would do anyway, and we'd have to pass the
1513 // right arguments to make sure it doesn't get no-op'ed.
1514 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1515 oldValue->setAlignment(Alignment.getQuantity());
1516
1517 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1518
1519 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1520 store->setAlignment(Alignment.getQuantity());
1521 }
1522
1523 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1524 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1525 value->setAlignment(Alignment.getQuantity());
1526
1527 CGF.EmitARCRelease(value, /*precise*/ false);
1528 }
1529
1530 void profileImpl(llvm::FoldingSetNodeID &id) const {
1531 // 2 is distinguishable from all pointers and byref flags
1532 id.AddInteger(2);
1533 }
1534};
1535
John McCallf0c11f72011-03-31 08:03:29 +00001536/// Emits the copy/dispose helpers for a __block variable with a
1537/// nontrivial copy constructor or destructor.
1538class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1539 QualType VarType;
1540 const Expr *CopyExpr;
1541
1542public:
1543 CXXByrefHelpers(CharUnits alignment, QualType type,
1544 const Expr *copyExpr)
1545 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1546
1547 bool needsCopy() const { return CopyExpr != 0; }
1548 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1549 llvm::Value *srcField) {
1550 if (!CopyExpr) return;
1551 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1552 }
1553
1554 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1555 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1556 CGF.PushDestructorCleanup(VarType, field);
1557 CGF.PopCleanupBlocks(cleanupDepth);
1558 }
1559
1560 void profileImpl(llvm::FoldingSetNodeID &id) const {
1561 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1562 }
1563};
1564} // end anonymous namespace
1565
1566static llvm::Constant *
1567generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001568 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001569 CodeGenModule::ByrefHelpers &byrefInfo) {
1570 ASTContext &Context = CGF.getContext();
1571
1572 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001573
John McCalld26bc762011-03-09 04:27:21 +00001574 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001575 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001576 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001577
John McCallf0c11f72011-03-31 08:03:29 +00001578 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001579 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Mike Stump45031c02009-03-06 02:29:21 +00001581 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001582 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1583 FunctionType::ExtInfo(),
1584 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001585
John McCallf0c11f72011-03-31 08:03:29 +00001586 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001587 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001588
Mike Stump3899a7f2009-06-05 23:26:36 +00001589 // FIXME: We'd like to put these into a mergable by content, with
1590 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001591 llvm::Function *Fn =
1592 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001593 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001594
1595 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001596 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001597
John McCallf0c11f72011-03-31 08:03:29 +00001598 FunctionDecl *FD = FunctionDecl::Create(Context,
1599 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001600 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001601 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001602 SC_Static,
1603 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001604 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001605
John McCallf0c11f72011-03-31 08:03:29 +00001606 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001607
John McCallf0c11f72011-03-31 08:03:29 +00001608 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001609 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001610
John McCallf0c11f72011-03-31 08:03:29 +00001611 // dst->x
1612 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1613 destField = CGF.Builder.CreateLoad(destField);
1614 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1615 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001616
John McCallf0c11f72011-03-31 08:03:29 +00001617 // src->x
1618 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1619 srcField = CGF.Builder.CreateLoad(srcField);
1620 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1621 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1622
1623 byrefInfo.emitCopy(CGF, destField, srcField);
1624 }
1625
1626 CGF.FinishFunction();
1627
1628 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001629}
1630
John McCallf0c11f72011-03-31 08:03:29 +00001631/// Build the copy helper for a __block variable.
1632static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001633 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001634 CodeGenModule::ByrefHelpers &info) {
1635 CodeGenFunction CGF(CGM);
1636 return generateByrefCopyHelper(CGF, byrefType, info);
1637}
1638
1639/// Generate code for a __block variable's dispose helper.
1640static llvm::Constant *
1641generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001642 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001643 CodeGenModule::ByrefHelpers &byrefInfo) {
1644 ASTContext &Context = CGF.getContext();
1645 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001646
John McCalld26bc762011-03-09 04:27:21 +00001647 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001648 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001649 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Mike Stump45031c02009-03-06 02:29:21 +00001651 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001652 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1653 FunctionType::ExtInfo(),
1654 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001655
John McCallf0c11f72011-03-31 08:03:29 +00001656 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001657 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001658
Mike Stump3899a7f2009-06-05 23:26:36 +00001659 // FIXME: We'd like to put these into a mergable by content, with
1660 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001661 llvm::Function *Fn =
1662 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001663 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001664 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001665
1666 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001667 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001668
John McCallf0c11f72011-03-31 08:03:29 +00001669 FunctionDecl *FD = FunctionDecl::Create(Context,
1670 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001671 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001672 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001673 SC_Static,
1674 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001675 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001676 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001677
John McCallf0c11f72011-03-31 08:03:29 +00001678 if (byrefInfo.needsDispose()) {
1679 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1680 V = CGF.Builder.CreateLoad(V);
1681 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1682 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001683
John McCallf0c11f72011-03-31 08:03:29 +00001684 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001685 }
Mike Stump45031c02009-03-06 02:29:21 +00001686
John McCallf0c11f72011-03-31 08:03:29 +00001687 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001688
John McCallf0c11f72011-03-31 08:03:29 +00001689 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001690}
1691
John McCallf0c11f72011-03-31 08:03:29 +00001692/// Build the dispose helper for a __block variable.
1693static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001694 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001695 CodeGenModule::ByrefHelpers &info) {
1696 CodeGenFunction CGF(CGM);
1697 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001698}
1699
John McCallf0c11f72011-03-31 08:03:29 +00001700///
1701template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001702 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001703 T &byrefInfo) {
1704 // Increase the field's alignment to be at least pointer alignment,
1705 // since the layout of the byref struct will guarantee at least that.
1706 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1707 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1708
1709 llvm::FoldingSetNodeID id;
1710 byrefInfo.Profile(id);
1711
1712 void *insertPos;
1713 CodeGenModule::ByrefHelpers *node
1714 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1715 if (node) return static_cast<T*>(node);
1716
1717 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1718 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1719
1720 T *copy = new (CGM.getContext()) T(byrefInfo);
1721 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1722 return copy;
1723}
1724
1725CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001726CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001727 const AutoVarEmission &emission) {
1728 const VarDecl &var = *emission.Variable;
1729 QualType type = var.getType();
1730
1731 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1732 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1733 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1734
1735 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1736 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1737 }
1738
John McCallf85e1932011-06-15 23:02:42 +00001739 // Otherwise, if we don't have a retainable type, there's nothing to do.
1740 // that the runtime does extra copies.
1741 if (!type->isObjCRetainableType()) return 0;
1742
1743 Qualifiers qs = type.getQualifiers();
1744
1745 // If we have lifetime, that dominates.
1746 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001747 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001748
1749 switch (lifetime) {
1750 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1751
1752 // These are just bits as far as the runtime is concerned.
1753 case Qualifiers::OCL_ExplicitNone:
1754 case Qualifiers::OCL_Autoreleasing:
1755 return 0;
1756
1757 // Tell the runtime that this is ARC __weak, called by the
1758 // byref routines.
1759 case Qualifiers::OCL_Weak: {
1760 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1761 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1762 }
1763
1764 // ARC __strong __block variables need to be retained.
1765 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001766 // Block pointers need to be copied, and there's no direct
1767 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001768 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001769 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001770 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1771
1772 // Otherwise, we transfer ownership of the retain from the stack
1773 // to the heap.
1774 } else {
1775 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1776 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1777 }
1778 }
1779 llvm_unreachable("fell out of lifetime switch!");
1780 }
1781
John McCallf0c11f72011-03-31 08:03:29 +00001782 BlockFieldFlags flags;
1783 if (type->isBlockPointerType()) {
1784 flags |= BLOCK_FIELD_IS_BLOCK;
1785 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1786 type->isObjCObjectPointerType()) {
1787 flags |= BLOCK_FIELD_IS_OBJECT;
1788 } else {
1789 return 0;
1790 }
1791
1792 if (type.isObjCGCWeak())
1793 flags |= BLOCK_FIELD_IS_WEAK;
1794
1795 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1796 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001797}
1798
John McCall5af02db2011-03-31 01:59:53 +00001799unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1800 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1801
1802 return ByRefValueInfo.find(VD)->second.second;
1803}
1804
1805llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1806 const VarDecl *V) {
1807 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1808 Loc = Builder.CreateLoad(Loc);
1809 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1810 V->getNameAsString());
1811 return Loc;
1812}
1813
1814/// BuildByRefType - This routine changes a __block variable declared as T x
1815/// into:
1816///
1817/// struct {
1818/// void *__isa;
1819/// void *__forwarding;
1820/// int32_t __flags;
1821/// int32_t __size;
1822/// void *__copy_helper; // only if needed
1823/// void *__destroy_helper; // only if needed
1824/// char padding[X]; // only if needed
1825/// T x;
1826/// } x
1827///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001828llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1829 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001830 if (Info.first)
1831 return Info.first;
1832
1833 QualType Ty = D->getType();
1834
Chris Lattner5f9e2722011-07-23 10:55:15 +00001835 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001836
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001837 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001838 llvm::StructType::create(getLLVMContext(),
1839 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001840
1841 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001842 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001843
1844 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001845 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001846
1847 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001848 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001849
1850 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001851 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001852
David Chisnall9595dae2012-04-04 13:07:13 +00001853 bool HasCopyAndDispose =
1854 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001855 if (HasCopyAndDispose) {
1856 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001857 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001858
1859 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001860 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001861 }
1862
1863 bool Packed = false;
1864 CharUnits Align = getContext().getDeclAlign(D);
1865 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1866 // We have to insert padding.
1867
1868 // The struct above has 2 32-bit integers.
1869 unsigned CurrentOffsetInBytes = 4 * 2;
1870
1871 // And either 2 or 4 pointers.
1872 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1873 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1874
1875 // Align the offset.
1876 unsigned AlignedOffsetInBytes =
1877 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1878
1879 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1880 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001881 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001882 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001883 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001884 if (NumPaddingBytes > 1)
1885 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1886
John McCall0774cb82011-05-15 01:53:33 +00001887 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001888
1889 // We want a packed struct.
1890 Packed = true;
1891 }
1892 }
1893
1894 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001895 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001896
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001897 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001898
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001899 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001900
John McCall0774cb82011-05-15 01:53:33 +00001901 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001902
1903 return Info.first;
1904}
1905
1906/// Initialize the structural components of a __block variable, i.e.
1907/// everything but the actual object.
1908void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001909 // Find the address of the local.
1910 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001911
John McCallf0c11f72011-03-31 08:03:29 +00001912 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001913 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001914 cast<llvm::PointerType>(addr->getType())->getElementType());
1915
1916 // Build the byref helpers if necessary. This is null if we don't need any.
1917 CodeGenModule::ByrefHelpers *helpers =
1918 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001919
1920 const VarDecl &D = *emission.Variable;
1921 QualType type = D.getType();
1922
John McCallf0c11f72011-03-31 08:03:29 +00001923 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001924
1925 // Initialize the 'isa', which is just 0 or 1.
1926 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001927 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001928 isa = 1;
1929 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1930 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1931
1932 // Store the address of the variable into its own forwarding pointer.
1933 Builder.CreateStore(addr,
1934 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1935
1936 // Blocks ABI:
1937 // c) the flags field is set to either 0 if no helper functions are
1938 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1939 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001940 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001941 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1942 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1943
John McCallf0c11f72011-03-31 08:03:29 +00001944 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1945 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001946 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1947
John McCallf0c11f72011-03-31 08:03:29 +00001948 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001949 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001950 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001951
1952 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001953 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001954 }
1955}
1956
John McCalld16c2cf2011-02-08 08:22:06 +00001957void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001958 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001959 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001960 V = Builder.CreateBitCast(V, Int8PtrTy);
1961 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001962 Builder.CreateCall2(F, V, N);
1963}
John McCall5af02db2011-03-31 01:59:53 +00001964
1965namespace {
1966 struct CallBlockRelease : EHScopeStack::Cleanup {
1967 llvm::Value *Addr;
1968 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1969
John McCallad346f42011-07-12 20:27:29 +00001970 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001971 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001972 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1973 }
1974 };
1975}
1976
1977/// Enter a cleanup to destroy a __block variable. Note that this
1978/// cleanup should be a no-op if the variable hasn't left the stack
1979/// yet; if a cleanup is required for the variable itself, that needs
1980/// to be done externally.
1981void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1982 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00001983 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001984 return;
1985
1986 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1987}
John McCall13db5cf2011-09-09 20:41:01 +00001988
1989/// Adjust the declaration of something from the blocks API.
1990static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1991 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001992 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00001993
1994 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1995 if (GV->isDeclaration() &&
1996 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1997 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1998}
1999
2000llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2001 if (BlockObjectDispose)
2002 return BlockObjectDispose;
2003
2004 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2005 llvm::FunctionType *fty
2006 = llvm::FunctionType::get(VoidTy, args, false);
2007 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2008 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2009 return BlockObjectDispose;
2010}
2011
2012llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2013 if (BlockObjectAssign)
2014 return BlockObjectAssign;
2015
2016 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2017 llvm::FunctionType *fty
2018 = llvm::FunctionType::get(VoidTy, args, false);
2019 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2020 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2021 return BlockObjectAssign;
2022}
2023
2024llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2025 if (NSConcreteGlobalBlock)
2026 return NSConcreteGlobalBlock;
2027
2028 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2029 Int8PtrTy->getPointerTo(), 0);
2030 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2031 return NSConcreteGlobalBlock;
2032}
2033
2034llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2035 if (NSConcreteStackBlock)
2036 return NSConcreteStackBlock;
2037
2038 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2039 Int8PtrTy->getPointerTo(), 0);
2040 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2041 return NSConcreteStackBlock;
2042}