blob: e713492cc0adf63a27432d7a1dc002f92a502c38 [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.
95 if (C.getLangOptions().ObjC1)
96 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,
218 const VarDecl *var) {
219 QualType type = var->getType();
220
221 // We can only do this if the variable is const.
222 if (!type.isConstQualified()) return 0;
223
John McCall461c9c12011-02-08 03:07:00 +0000224 // Furthermore, in C++ we have to worry about mutable fields:
225 // C++ [dcl.type.cv]p4:
226 // Except that any class member declared mutable can be
227 // modified, any attempt to modify a const object during its
228 // lifetime results in undefined behavior.
229 if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000230 return 0;
231
232 // If the variable doesn't have any initializer (shouldn't this be
233 // invalid?), it's not clear what we should do. Maybe capture as
234 // zero?
235 const Expr *init = var->getInit();
236 if (!init) return 0;
237
238 return CGM.EmitConstantExpr(init, var->getType());
239}
240
241/// Get the low bit of a nonzero character count. This is the
242/// alignment of the nth byte if the 0th byte is universally aligned.
243static CharUnits getLowBit(CharUnits v) {
244 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
245}
246
247static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000249 ASTContext &C = CGM.getContext();
250
251 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
252 CharUnits ptrSize, ptrAlign, intSize, intAlign;
253 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
254 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
255
256 // Are there crazy embedded platforms where this isn't true?
257 assert(intSize <= ptrSize && "layout assumptions horribly violated");
258
259 CharUnits headerSize = ptrSize;
260 if (2 * intSize < ptrAlign) headerSize += ptrSize;
261 else headerSize += 2 * intSize;
262 headerSize += 2 * ptrSize;
263
264 info.BlockAlign = ptrAlign;
265 info.BlockSize = headerSize;
266
267 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000268 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
269 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000270 elementTypes.push_back(i8p);
271 elementTypes.push_back(intTy);
272 elementTypes.push_back(intTy);
273 elementTypes.push_back(i8p);
274 elementTypes.push_back(CGM.getBlockDescriptorType());
275
276 assert(elementTypes.size() == BlockHeaderSize);
277}
278
279/// Compute the layout of the given block. Attempts to lay the block
280/// out with minimal space requirements.
281static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
282 ASTContext &C = CGM.getContext();
283 const BlockDecl *block = info.getBlockDecl();
284
Chris Lattner5f9e2722011-07-23 10:55:15 +0000285 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000286 initializeForBlockHeader(CGM, info, elementTypes);
287
288 if (!block->hasCaptures()) {
289 info.StructureType =
290 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
291 info.CanBeGlobal = true;
292 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000293 }
Mike Stump00470a12009-03-05 08:32:30 +0000294
John McCall6b5a61b2011-02-07 10:33:21 +0000295 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000296 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000297 layout.reserve(block->capturesCXXThis() +
298 (block->capture_end() - block->capture_begin()));
299
300 CharUnits maxFieldAlign;
301
302 // First, 'this'.
303 if (block->capturesCXXThis()) {
304 const DeclContext *DC = block->getDeclContext();
305 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
306 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000307 QualType thisType;
308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
309 thisType = C.getPointerType(C.getRecordType(RD));
310 else
311 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000312
Jay Foadef6de3d2011-07-11 09:56:20 +0000313 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000314 std::pair<CharUnits,CharUnits> tinfo
315 = CGM.getContext().getTypeInfoInChars(thisType);
316 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
317
318 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
319 }
320
321 // Next, all the block captures.
322 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
323 ce = block->capture_end(); ci != ce; ++ci) {
324 const VarDecl *variable = ci->getVariable();
325
326 if (ci->isByRef()) {
327 // We have to copy/dispose of the __block reference.
328 info.NeedsCopyDispose = true;
329
John McCall6b5a61b2011-02-07 10:33:21 +0000330 // Just use void* instead of a pointer to the byref type.
331 QualType byRefPtrTy = C.VoidPtrTy;
332
Jay Foadef6de3d2011-07-11 09:56:20 +0000333 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000334 std::pair<CharUnits,CharUnits> tinfo
335 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
336 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
337
338 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
339 &*ci, llvmType));
340 continue;
341 }
342
343 // Otherwise, build a layout chunk with the size and alignment of
344 // the declaration.
345 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, variable)) {
346 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
347 continue;
348 }
349
John McCallf85e1932011-06-15 23:02:42 +0000350 // If we have a lifetime qualifier, honor it for capture purposes.
351 // That includes *not* copying it if it's __unsafe_unretained.
352 if (Qualifiers::ObjCLifetime lifetime
353 = variable->getType().getObjCLifetime()) {
354 switch (lifetime) {
355 case Qualifiers::OCL_None: llvm_unreachable("impossible");
356 case Qualifiers::OCL_ExplicitNone:
357 case Qualifiers::OCL_Autoreleasing:
358 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000359
John McCallf85e1932011-06-15 23:02:42 +0000360 case Qualifiers::OCL_Strong:
361 case Qualifiers::OCL_Weak:
362 info.NeedsCopyDispose = true;
363 }
364
365 // Block pointers require copy/dispose. So do Objective-C pointers.
366 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000367 info.NeedsCopyDispose = true;
368
369 // So do types that require non-trivial copy construction.
370 } else if (ci->hasCopyExpr()) {
371 info.NeedsCopyDispose = true;
372 info.HasCXXObject = true;
373
374 // And so do types with destructors.
375 } else if (CGM.getLangOptions().CPlusPlus) {
376 if (const CXXRecordDecl *record =
377 variable->getType()->getAsCXXRecordDecl()) {
378 if (!record->hasTrivialDestructor()) {
379 info.HasCXXObject = true;
380 info.NeedsCopyDispose = true;
381 }
382 }
383 }
384
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000385 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000386 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000387 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000388
John McCall6b5a61b2011-02-07 10:33:21 +0000389 maxFieldAlign = std::max(maxFieldAlign, align);
390
Jay Foadef6de3d2011-07-11 09:56:20 +0000391 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000392 CGM.getTypes().ConvertTypeForMem(VT);
393
John McCall6b5a61b2011-02-07 10:33:21 +0000394 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
395 }
396
397 // If that was everything, we're done here.
398 if (layout.empty()) {
399 info.StructureType =
400 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
401 info.CanBeGlobal = true;
402 return;
403 }
404
405 // Sort the layout by alignment. We have to use a stable sort here
406 // to get reproducible results. There should probably be an
407 // llvm::array_pod_stable_sort.
408 std::stable_sort(layout.begin(), layout.end());
409
410 CharUnits &blockSize = info.BlockSize;
411 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
412
413 // Assuming that the first byte in the header is maximally aligned,
414 // get the alignment of the first byte following the header.
415 CharUnits endAlign = getLowBit(blockSize);
416
417 // If the end of the header isn't satisfactorily aligned for the
418 // maximum thing, look for things that are okay with the header-end
419 // alignment, and keep appending them until we get something that's
420 // aligned right. This algorithm is only guaranteed optimal if
421 // that condition is satisfied at some point; otherwise we can get
422 // things like:
423 // header // next byte has alignment 4
424 // something_with_size_5; // next byte has alignment 1
425 // something_with_alignment_8;
426 // which has 7 bytes of padding, as opposed to the naive solution
427 // which might have less (?).
428 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000430 li = layout.begin() + 1, le = layout.end();
431
432 // Look for something that the header end is already
433 // satisfactorily aligned for.
434 for (; li != le && endAlign < li->Alignment; ++li)
435 ;
436
437 // If we found something that's naturally aligned for the end of
438 // the header, keep adding things...
439 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000441 for (; li != le; ++li) {
442 assert(endAlign >= li->Alignment);
443
444 li->setIndex(info, elementTypes.size());
445 elementTypes.push_back(li->Type);
446 blockSize += li->Size;
447 endAlign = getLowBit(blockSize);
448
449 // ...until we get to the alignment of the maximum field.
450 if (endAlign >= maxFieldAlign)
451 break;
452 }
453
454 // Don't re-append everything we just appended.
455 layout.erase(first, li);
456 }
457 }
458
459 // At this point, we just have to add padding if the end align still
460 // isn't aligned right.
461 if (endAlign < maxFieldAlign) {
462 CharUnits padding = maxFieldAlign - endAlign;
463
John McCall5936e332011-02-15 09:22:45 +0000464 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
465 padding.getQuantity()));
John McCall6b5a61b2011-02-07 10:33:21 +0000466 blockSize += padding;
467
468 endAlign = getLowBit(blockSize);
469 assert(endAlign >= maxFieldAlign);
470 }
471
472 // Slam everything else on now. This works because they have
473 // strictly decreasing alignment and we expect that size is always a
474 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000475 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000476 li = layout.begin(), le = layout.end(); li != le; ++li) {
477 assert(endAlign >= li->Alignment);
478 li->setIndex(info, elementTypes.size());
479 elementTypes.push_back(li->Type);
480 blockSize += li->Size;
481 endAlign = getLowBit(blockSize);
482 }
483
484 info.StructureType =
485 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
486}
487
John McCall1a343eb2011-11-10 08:15:53 +0000488/// Enter the scope of a block. This should be run at the entrance to
489/// a full-expression so that the block's cleanups are pushed at the
490/// right place in the stack.
491static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
492 // Allocate the block info and place it at the head of the list.
493 CGBlockInfo &blockInfo =
494 *new CGBlockInfo(block, CGF.CurFn->getName());
495 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
496 CGF.FirstBlockInfo = &blockInfo;
497
498 // Compute information about the layout, etc., of this block,
499 // pushing cleanups as necessary.
500 computeBlockInfo(CGF.CGM, blockInfo);
501
502 // Nothing else to do if it can be global.
503 if (blockInfo.CanBeGlobal) return;
504
505 // Make the allocation for the block.
506 blockInfo.Address =
507 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
508 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
509
510 // If there are cleanups to emit, enter them (but inactive).
511 if (!blockInfo.NeedsCopyDispose) return;
512
513 // Walk through the captures (in order) and find the ones not
514 // captured by constant.
515 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
516 ce = block->capture_end(); ci != ce; ++ci) {
517 // Ignore __block captures; there's nothing special in the
518 // on-stack block that we need to do for them.
519 if (ci->isByRef()) continue;
520
521 // Ignore variables that are constant-captured.
522 const VarDecl *variable = ci->getVariable();
523 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
524 if (capture.isConstant()) continue;
525
526 // Ignore objects that aren't destructed.
527 QualType::DestructionKind dtorKind =
528 variable->getType().isDestructedType();
529 if (dtorKind == QualType::DK_none) continue;
530
531 CodeGenFunction::Destroyer *destroyer;
532
533 // Block captures count as local values and have imprecise semantics.
534 // They also can't be arrays, so need to worry about that.
535 if (dtorKind == QualType::DK_objc_strong_lifetime) {
536 destroyer = &CodeGenFunction::destroyARCStrongImprecise;
537 } else {
538 destroyer = &CGF.getDestroyer(dtorKind);
539 }
540
541 // GEP down to the address.
542 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
543 capture.getIndex());
544
John McCall6f103ba2011-11-10 10:43:54 +0000545 // We can use that GEP as the dominating IP.
546 if (!blockInfo.DominatingIP)
547 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
548
John McCall1a343eb2011-11-10 08:15:53 +0000549 CleanupKind cleanupKind = InactiveNormalCleanup;
550 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
551 if (useArrayEHCleanup)
552 cleanupKind = InactiveNormalAndEHCleanup;
553
554 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
555 *destroyer, useArrayEHCleanup);
556
557 // Remember where that cleanup was.
558 capture.setCleanup(CGF.EHStack.stable_begin());
559 }
560}
561
562/// Enter a full-expression with a non-trivial number of objects to
563/// clean up. This is in this file because, at the moment, the only
564/// kind of cleanup object is a BlockDecl*.
565void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
566 assert(E->getNumObjects() != 0);
567 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
568 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
569 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
570 enterBlockScope(*this, *i);
571 }
572}
573
574/// Find the layout for the given block in a linked list and remove it.
575static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
576 const BlockDecl *block) {
577 while (true) {
578 assert(head && *head);
579 CGBlockInfo *cur = *head;
580
581 // If this is the block we're looking for, splice it out of the list.
582 if (cur->getBlockDecl() == block) {
583 *head = cur->NextBlockInfo;
584 return cur;
585 }
586
587 head = &cur->NextBlockInfo;
588 }
589}
590
591/// Destroy a chain of block layouts.
592void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
593 assert(head && "destroying an empty chain");
594 do {
595 CGBlockInfo *cur = head;
596 head = cur->NextBlockInfo;
597 delete cur;
598 } while (head != 0);
599}
600
John McCall6b5a61b2011-02-07 10:33:21 +0000601/// Emit a block literal expression in the current function.
602llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000603 // If the block has no captures, we won't have a pre-computed
604 // layout for it.
605 if (!blockExpr->getBlockDecl()->hasCaptures()) {
606 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
607 computeBlockInfo(CGM, blockInfo);
608 blockInfo.BlockExpression = blockExpr;
609 return EmitBlockLiteral(blockInfo);
610 }
John McCall6b5a61b2011-02-07 10:33:21 +0000611
John McCall1a343eb2011-11-10 08:15:53 +0000612 // Find the block info for this block and take ownership of it.
613 llvm::OwningPtr<CGBlockInfo> blockInfo;
614 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
615 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000616
John McCall1a343eb2011-11-10 08:15:53 +0000617 blockInfo->BlockExpression = blockExpr;
618 return EmitBlockLiteral(*blockInfo);
619}
620
621llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
622 // Using the computed layout, generate the actual block function.
John McCall6b5a61b2011-02-07 10:33:21 +0000623 llvm::Constant *blockFn
624 = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
625 CurFuncDecl, LocalDeclMap);
John McCall5936e332011-02-15 09:22:45 +0000626 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000627
628 // If there is nothing to capture, we can emit this as a global block.
629 if (blockInfo.CanBeGlobal)
630 return buildGlobalBlock(CGM, blockInfo, blockFn);
631
632 // Otherwise, we have to emit this as a local block.
633
634 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000635 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000636
637 // Build the block descriptor.
638 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
639
John McCall1a343eb2011-11-10 08:15:53 +0000640 llvm::AllocaInst *blockAddr = blockInfo.Address;
641 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000642
643 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000644 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000645 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
646 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000647 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000648
649 // Initialize the block literal.
650 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000651 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000652 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000653 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000654 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
655 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
656 "block.invoke"));
657 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
658 "block.descriptor"));
659
660 // Finally, capture all the values into the block.
661 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
662
663 // First, 'this'.
664 if (blockDecl->capturesCXXThis()) {
665 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
666 blockInfo.CXXThisIndex,
667 "block.captured-this.addr");
668 Builder.CreateStore(LoadCXXThis(), addr);
669 }
670
671 // Next, captured variables.
672 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
673 ce = blockDecl->capture_end(); ci != ce; ++ci) {
674 const VarDecl *variable = ci->getVariable();
675 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
676
677 // Ignore constant captures.
678 if (capture.isConstant()) continue;
679
680 QualType type = variable->getType();
681
682 // This will be a [[type]]*, except that a byref entry will just be
683 // an i8**.
684 llvm::Value *blockField =
685 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
686 "block.captured");
687
688 // Compute the address of the thing we're going to move into the
689 // block literal.
690 llvm::Value *src;
691 if (ci->isNested()) {
692 // We need to use the capture from the enclosing block.
693 const CGBlockInfo::Capture &enclosingCapture =
694 BlockInfo->getCapture(variable);
695
696 // This is a [[type]]*, except that a byref entry wil just be an i8**.
697 src = Builder.CreateStructGEP(LoadBlockStruct(),
698 enclosingCapture.getIndex(),
699 "block.capture.addr");
700 } else {
701 // This is a [[type]]*.
702 src = LocalDeclMap[variable];
703 }
704
705 // For byrefs, we just write the pointer to the byref struct into
706 // the block field. There's no need to chase the forwarding
707 // pointer at this point, since we're building something that will
708 // live a shorter life than the stack byref anyway.
709 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000710 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000711 if (ci->isNested())
712 src = Builder.CreateLoad(src, "byref.capture");
713 else
John McCall5936e332011-02-15 09:22:45 +0000714 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000715
John McCall5936e332011-02-15 09:22:45 +0000716 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000717 Builder.CreateStore(src, blockField);
718
719 // If we have a copy constructor, evaluate that into the block field.
720 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
721 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
722
723 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000724 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000725 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
726
727 // Otherwise, fake up a POD copy into the block field.
728 } else {
John McCallf85e1932011-06-15 23:02:42 +0000729 // Fake up a new variable so that EmitScalarInit doesn't think
730 // we're referring to the variable in its own initializer.
731 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000732 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000733
John McCallbb699b02011-02-07 18:37:40 +0000734 // We use one of these or the other depending on whether the
735 // reference is nested.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000736 DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValue,
John McCallbb699b02011-02-07 18:37:40 +0000737 SourceLocation());
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000738 BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
John McCallbb699b02011-02-07 18:37:40 +0000739 VK_LValue, SourceLocation(), /*byref*/ false);
740
741 Expr *declRef =
742 (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
743
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000744 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallbb699b02011-02-07 18:37:40 +0000745 declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000746 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000747 MakeAddrLValue(blockField, type,
Eli Friedman225bf772011-09-30 18:19:16 +0000748 getContext().getDeclAlign(variable)
749 .getQuantity()),
John McCalldf045202011-03-08 09:38:48 +0000750 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000751 }
752
John McCall1a343eb2011-11-10 08:15:53 +0000753 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000754 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000755 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
756 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000757 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000758 }
John McCall6b5a61b2011-02-07 10:33:21 +0000759 }
760
761 // Cast to the converted block-pointer type, which happens (somewhat
762 // unfortunately) to be a pointer to function type.
763 llvm::Value *result =
764 Builder.CreateBitCast(blockAddr,
765 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000766
John McCall6b5a61b2011-02-07 10:33:21 +0000767 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000768}
769
770
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000771llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000772 if (BlockDescriptorType)
773 return BlockDescriptorType;
774
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000775 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000776 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000777
Mike Stumpab695142009-02-13 15:16:56 +0000778 // struct __block_descriptor {
779 // unsigned long reserved;
780 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000781 //
782 // // later, the following will be added
783 //
784 // struct {
785 // void (*copyHelper)();
786 // void (*copyHelper)();
787 // } helpers; // !!! optional
788 //
789 // const char *signature; // the block signature
790 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000791 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000792 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000793 llvm::StructType::create("struct.__block_descriptor",
794 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000795
John McCall6b5a61b2011-02-07 10:33:21 +0000796 // Now form a pointer to that.
797 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000798 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000799}
800
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000801llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000802 if (GenericBlockLiteralType)
803 return GenericBlockLiteralType;
804
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000805 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000806
Mike Stump9b8a7972009-02-13 15:25:34 +0000807 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000808 // void *__isa;
809 // int __flags;
810 // int __reserved;
811 // void (*__invoke)(void *);
812 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000813 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000814 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000815 llvm::StructType::create("struct.__block_literal_generic",
816 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
817 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000818
Mike Stump9b8a7972009-02-13 15:25:34 +0000819 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000820}
821
Mike Stumpbd65cac2009-02-19 01:01:04 +0000822
Anders Carlssona1736c02009-12-24 21:13:40 +0000823RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
824 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000825 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000826 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000827
Anders Carlssonacfde802009-02-12 00:39:25 +0000828 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
829
830 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000831 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000832 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000833
834 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000835 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000836 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
837
838 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000839 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000840
Benjamin Kramer578faa82011-09-27 21:06:10 +0000841 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000842
Anders Carlssonacfde802009-02-12 00:39:25 +0000843 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000844 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000845 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000846
Anders Carlsson782f3972009-04-08 23:13:16 +0000847 QualType FnType = BPT->getPointeeType();
848
Anders Carlssonacfde802009-02-12 00:39:25 +0000849 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000850 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000851 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000852
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000853 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000854 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000855
John McCall64cd2322011-03-09 08:39:33 +0000856 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
Eli Friedmanc55db3b2011-08-09 17:38:12 +0000857 const CGFunctionInfo &FnInfo = CGM.getTypes().getFunctionInfo(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000859 // Cast the function pointer to the right type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000860 llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000861 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Chris Lattner2acc6e32011-07-18 04:24:23 +0000863 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000864 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Anders Carlssonacfde802009-02-12 00:39:25 +0000866 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000867 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000868}
Anders Carlssond5cab542009-02-12 17:55:02 +0000869
John McCall6b5a61b2011-02-07 10:33:21 +0000870llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
871 bool isByRef) {
872 assert(BlockInfo && "evaluating block ref without block information?");
873 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000874
John McCall6b5a61b2011-02-07 10:33:21 +0000875 // Handle constant captures.
876 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000877
John McCall6b5a61b2011-02-07 10:33:21 +0000878 llvm::Value *addr =
879 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
880 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000881
John McCall6b5a61b2011-02-07 10:33:21 +0000882 if (isByRef) {
883 // addr should be a void** right now. Load, then cast the result
884 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000885
John McCall6b5a61b2011-02-07 10:33:21 +0000886 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000887 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000888 = llvm::PointerType::get(BuildByRefType(variable), 0);
889 addr = Builder.CreateBitCast(addr, byrefPointerType,
890 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000891
John McCall6b5a61b2011-02-07 10:33:21 +0000892 // Follow the forwarding pointer.
893 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
894 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000895
John McCall6b5a61b2011-02-07 10:33:21 +0000896 // Cast back to byref* and GEP over to the actual object.
897 addr = Builder.CreateBitCast(addr, byrefPointerType);
898 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
899 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000900 }
901
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000902 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000903 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000904
John McCall6b5a61b2011-02-07 10:33:21 +0000905 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000906}
907
Mike Stump67a64482009-02-14 22:16:35 +0000908llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000909CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000910 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000911 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
912 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 // Compute information about the layout, etc., of this block.
John McCalld16c2cf2011-02-08 08:22:06 +0000915 computeBlockInfo(*this, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000916
John McCall6b5a61b2011-02-07 10:33:21 +0000917 // Using that metadata, generate the actual block function.
918 llvm::Constant *blockFn;
919 {
920 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000921 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
922 blockInfo,
923 0, LocalDeclMap);
John McCall6b5a61b2011-02-07 10:33:21 +0000924 }
John McCall5936e332011-02-15 09:22:45 +0000925 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000926
John McCalld16c2cf2011-02-08 08:22:06 +0000927 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000928}
929
John McCall6b5a61b2011-02-07 10:33:21 +0000930static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
931 const CGBlockInfo &blockInfo,
932 llvm::Constant *blockFn) {
933 assert(blockInfo.CanBeGlobal);
934
935 // Generate the constants for the block literal initializer.
936 llvm::Constant *fields[BlockHeaderSize];
937
938 // isa
939 fields[0] = CGM.getNSConcreteGlobalBlock();
940
941 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000942 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
943 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
944
John McCall5936e332011-02-15 09:22:45 +0000945 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000946
947 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000948 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000949
950 // Function
951 fields[3] = blockFn;
952
953 // Descriptor
954 fields[4] = buildBlockDescriptor(CGM, blockInfo);
955
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000956 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000957
958 llvm::GlobalVariable *literal =
959 new llvm::GlobalVariable(CGM.getModule(),
960 init->getType(),
961 /*constant*/ true,
962 llvm::GlobalVariable::InternalLinkage,
963 init,
964 "__block_literal_global");
965 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
966
967 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000968 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +0000969 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
970 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000971}
972
Mike Stump00470a12009-03-05 08:32:30 +0000973llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +0000974CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
975 const CGBlockInfo &blockInfo,
976 const Decl *outerFnDecl,
977 const DeclMapTy &ldm) {
978 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +0000979
Devang Patel6d1155b2011-03-07 21:53:18 +0000980 // Check if we should generate debug info for this block function.
981 if (CGM.getModuleDebugInfo())
982 DebugInfo = CGM.getModuleDebugInfo();
983
John McCall6b5a61b2011-02-07 10:33:21 +0000984 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Mike Stump7f28a9c2009-03-13 23:34:28 +0000986 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +0000987 // to be local to this function as well, in case they're directly
988 // referenced in a block.
989 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
990 const VarDecl *var = dyn_cast<VarDecl>(i->first);
991 if (var && !var->hasLocalStorage())
992 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000993 }
994
John McCall6b5a61b2011-02-07 10:33:21 +0000995 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +0000996
John McCall6b5a61b2011-02-07 10:33:21 +0000997 // Build the argument list.
998 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +0000999
John McCall6b5a61b2011-02-07 10:33:21 +00001000 // The first argument is the block pointer. Just take it as a void*
1001 // and cast it later.
1002 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001003 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001004
John McCall8178df32011-02-22 22:38:33 +00001005 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1006 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001007 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001008
John McCall6b5a61b2011-02-07 10:33:21 +00001009 // Now add the rest of the parameters.
1010 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1011 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001012 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001013
John McCall6b5a61b2011-02-07 10:33:21 +00001014 // Create the function declaration.
1015 const FunctionProtoType *fnType =
1016 cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
1017 const CGFunctionInfo &fnInfo =
1018 CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
1019 fnType->getExtInfo());
John McCall64cd2322011-03-09 08:39:33 +00001020 if (CGM.ReturnTypeUsesSRet(fnInfo))
1021 blockInfo.UsesStret = true;
1022
Chris Lattner2acc6e32011-07-18 04:24:23 +00001023 llvm::FunctionType *fnLLVMType =
John McCall6b5a61b2011-02-07 10:33:21 +00001024 CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +00001025
John McCall6b5a61b2011-02-07 10:33:21 +00001026 MangleBuffer name;
1027 CGM.getBlockMangledName(GD, name, blockDecl);
1028 llvm::Function *fn =
1029 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1030 name.getString(), &CGM.getModule());
1031 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001032
John McCall6b5a61b2011-02-07 10:33:21 +00001033 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001034 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001035 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001036 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001037
John McCall8178df32011-02-22 22:38:33 +00001038 // Okay. Undo some of what StartFunction did.
1039
1040 // Pull the 'self' reference out of the local decl map.
1041 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1042 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001043 BlockPointer = Builder.CreateBitCast(blockAddr,
1044 blockInfo.StructureType->getPointerTo(),
1045 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001046
John McCallea1471e2010-05-20 01:18:31 +00001047 // If we have a C++ 'this' reference, go ahead and force it into
1048 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001049 if (blockDecl->capturesCXXThis()) {
1050 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1051 blockInfo.CXXThisIndex,
1052 "block.captured-this");
1053 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001054 }
1055
John McCall6b5a61b2011-02-07 10:33:21 +00001056 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1057 // appease it.
1058 if (const ObjCMethodDecl *method
1059 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1060 const VarDecl *self = method->getSelfDecl();
1061
1062 // There might not be a capture for 'self', but if there is...
1063 if (blockInfo.Captures.count(self)) {
1064 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1065 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1066 capture.getIndex(),
1067 "block.captured-self");
1068 LocalDeclMap[self] = selfAddr;
1069 }
1070 }
1071
1072 // Also force all the constant captures.
1073 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1074 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1075 const VarDecl *variable = ci->getVariable();
1076 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1077 if (!capture.isConstant()) continue;
1078
1079 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1080
1081 llvm::AllocaInst *alloca =
1082 CreateMemTemp(variable->getType(), "block.captured-const");
1083 alloca->setAlignment(align);
1084
1085 Builder.CreateStore(capture.getConstant(), alloca, align);
1086
1087 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001088 }
1089
Mike Stumpb289b3f2009-10-01 22:29:41 +00001090 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
1091 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1092 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1093 --entry_ptr;
1094
John McCall6b5a61b2011-02-07 10:33:21 +00001095 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001096
Mike Stumpde8c5c72009-10-01 00:27:30 +00001097 // Remember where we were...
1098 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001099
Mike Stumpde8c5c72009-10-01 00:27:30 +00001100 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001101 ++entry_ptr;
1102 Builder.SetInsertPoint(entry, entry_ptr);
1103
John McCall6b5a61b2011-02-07 10:33:21 +00001104 // Emit debug information for all the BlockDeclRefDecls.
1105 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001106 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001107 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1108 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1109 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001110 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001111
1112 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1113 if (capture.isConstant()) {
1114 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1115 Builder);
1116 continue;
Mike Stumpb1a6e682009-09-30 02:43:10 +00001117 }
John McCall6b5a61b2011-02-07 10:33:21 +00001118
John McCall8178df32011-02-22 22:38:33 +00001119 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
John McCall6b5a61b2011-02-07 10:33:21 +00001120 Builder, blockInfo);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001121 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001122 }
John McCall6b5a61b2011-02-07 10:33:21 +00001123
Mike Stumpde8c5c72009-10-01 00:27:30 +00001124 // And resume where we left off.
1125 if (resume == 0)
1126 Builder.ClearInsertionPoint();
1127 else
1128 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001129
John McCall6b5a61b2011-02-07 10:33:21 +00001130 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001131
John McCall6b5a61b2011-02-07 10:33:21 +00001132 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001133}
Mike Stumpa99038c2009-02-28 09:07:16 +00001134
John McCall6b5a61b2011-02-07 10:33:21 +00001135/*
1136 notes.push_back(HelperInfo());
1137 HelperInfo &note = notes.back();
1138 note.index = capture.getIndex();
1139 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1140 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 if (ci->isByRef()) {
1143 note.flag = BLOCK_FIELD_IS_BYREF;
1144 if (type.isObjCGCWeak())
1145 note.flag |= BLOCK_FIELD_IS_WEAK;
1146 } else if (type->isBlockPointerType()) {
1147 note.flag = BLOCK_FIELD_IS_BLOCK;
1148 } else {
1149 note.flag = BLOCK_FIELD_IS_OBJECT;
1150 }
1151 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001152
Mike Stump00470a12009-03-05 08:32:30 +00001153
Mike Stumpa99038c2009-02-28 09:07:16 +00001154
John McCall6b5a61b2011-02-07 10:33:21 +00001155llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001156CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001157 ASTContext &C = getContext();
1158
1159 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001160 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1161 args.push_back(&dstDecl);
1162 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1163 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Mike Stumpa4f668f2009-03-06 01:33:24 +00001165 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001166 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001167
John McCall6b5a61b2011-02-07 10:33:21 +00001168 // FIXME: it would be nice if these were mergeable with things with
1169 // identical semantics.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001170 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001171
1172 llvm::Function *Fn =
1173 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001174 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001175
1176 IdentifierInfo *II
1177 = &CGM.getContext().Idents.get("__copy_helper_block_");
1178
Devang Patel58dc5ca2011-05-02 20:37:08 +00001179 // Check if we should generate debug info for this block helper function.
1180 if (CGM.getModuleDebugInfo())
1181 DebugInfo = CGM.getModuleDebugInfo();
1182
John McCall6b5a61b2011-02-07 10:33:21 +00001183 FunctionDecl *FD = FunctionDecl::Create(C,
1184 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001185 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001186 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001187 SC_Static,
1188 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001189 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001190 true);
John McCalld26bc762011-03-09 04:27:21 +00001191 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001192
Chris Lattner2acc6e32011-07-18 04:24:23 +00001193 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001194
John McCalld26bc762011-03-09 04:27:21 +00001195 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001196 src = Builder.CreateLoad(src);
1197 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001198
John McCalld26bc762011-03-09 04:27:21 +00001199 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001200 dst = Builder.CreateLoad(dst);
1201 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001202
John McCall6b5a61b2011-02-07 10:33:21 +00001203 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001204
John McCall6b5a61b2011-02-07 10:33:21 +00001205 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1206 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1207 const VarDecl *variable = ci->getVariable();
1208 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001209
John McCall6b5a61b2011-02-07 10:33:21 +00001210 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1211 if (capture.isConstant()) continue;
1212
1213 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001214 BlockFieldFlags flags;
1215
1216 bool isARCWeakCapture = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001217
1218 if (copyExpr) {
1219 assert(!ci->isByRef());
1220 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001221
John McCall6b5a61b2011-02-07 10:33:21 +00001222 } else if (ci->isByRef()) {
1223 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001224 if (type.isObjCGCWeak())
1225 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001226
John McCallf85e1932011-06-15 23:02:42 +00001227 } else if (type->isObjCRetainableType()) {
1228 flags = BLOCK_FIELD_IS_OBJECT;
1229 if (type->isBlockPointerType())
1230 flags = BLOCK_FIELD_IS_BLOCK;
1231
1232 // Special rules for ARC captures:
1233 if (getLangOptions().ObjCAutoRefCount) {
1234 Qualifiers qs = type.getQualifiers();
1235
1236 // Don't generate special copy logic for a captured object
1237 // unless it's __strong or __weak.
1238 if (!qs.hasStrongOrWeakObjCLifetime())
1239 continue;
1240
1241 // Support __weak direct captures.
1242 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1243 isARCWeakCapture = true;
1244 }
1245 } else {
1246 continue;
1247 }
John McCall6b5a61b2011-02-07 10:33:21 +00001248
1249 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001250 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1251 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001252
1253 // If there's an explicit copy expression, we do that.
1254 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001255 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCallf85e1932011-06-15 23:02:42 +00001256 } else if (isARCWeakCapture) {
1257 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001258 } else {
1259 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall5936e332011-02-15 09:22:45 +00001260 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1261 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001262 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
John McCallf85e1932011-06-15 23:02:42 +00001263 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
Mike Stump08920992009-03-07 02:35:30 +00001264 }
1265 }
1266
John McCalld16c2cf2011-02-08 08:22:06 +00001267 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001268
John McCall5936e332011-02-15 09:22:45 +00001269 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001270}
1271
John McCall6b5a61b2011-02-07 10:33:21 +00001272llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001273CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001274 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001275
John McCall6b5a61b2011-02-07 10:33:21 +00001276 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001277 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1278 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Mike Stumpa4f668f2009-03-06 01:33:24 +00001280 const CGFunctionInfo &FI =
John McCall6b5a61b2011-02-07 10:33:21 +00001281 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001282
Mike Stump3899a7f2009-06-05 23:26:36 +00001283 // FIXME: We'd like to put these into a mergable by content, with
1284 // internal linkage.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001285 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001286
1287 llvm::Function *Fn =
1288 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001289 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001290
Devang Patel58dc5ca2011-05-02 20:37:08 +00001291 // Check if we should generate debug info for this block destroy function.
1292 if (CGM.getModuleDebugInfo())
1293 DebugInfo = CGM.getModuleDebugInfo();
1294
Mike Stumpa4f668f2009-03-06 01:33:24 +00001295 IdentifierInfo *II
1296 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1297
John McCall6b5a61b2011-02-07 10:33:21 +00001298 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001299 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001300 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001301 SC_Static,
1302 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001303 false, true);
John McCalld26bc762011-03-09 04:27:21 +00001304 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001305
Chris Lattner2acc6e32011-07-18 04:24:23 +00001306 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001307
John McCalld26bc762011-03-09 04:27:21 +00001308 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001309 src = Builder.CreateLoad(src);
1310 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001311
John McCall6b5a61b2011-02-07 10:33:21 +00001312 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1313
John McCalld16c2cf2011-02-08 08:22:06 +00001314 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001315
1316 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1317 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1318 const VarDecl *variable = ci->getVariable();
1319 QualType type = variable->getType();
1320
1321 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1322 if (capture.isConstant()) continue;
1323
John McCalld16c2cf2011-02-08 08:22:06 +00001324 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001325 const CXXDestructorDecl *dtor = 0;
1326
John McCallf85e1932011-06-15 23:02:42 +00001327 bool isARCWeakCapture = false;
1328
John McCall6b5a61b2011-02-07 10:33:21 +00001329 if (ci->isByRef()) {
1330 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001331 if (type.isObjCGCWeak())
1332 flags |= BLOCK_FIELD_IS_WEAK;
1333 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1334 if (record->hasTrivialDestructor())
1335 continue;
1336 dtor = record->getDestructor();
1337 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001338 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001339 if (type->isBlockPointerType())
1340 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001341
John McCallf85e1932011-06-15 23:02:42 +00001342 // Special rules for ARC captures.
1343 if (getLangOptions().ObjCAutoRefCount) {
1344 Qualifiers qs = type.getQualifiers();
1345
1346 // Don't generate special dispose logic for a captured object
1347 // unless it's __strong or __weak.
1348 if (!qs.hasStrongOrWeakObjCLifetime())
1349 continue;
1350
1351 // Support __weak direct captures.
1352 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
1353 isARCWeakCapture = true;
1354 }
1355 } else {
1356 continue;
1357 }
John McCall6b5a61b2011-02-07 10:33:21 +00001358
1359 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001360 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001361
1362 // If there's an explicit copy expression, we do that.
1363 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001364 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001365
John McCallf85e1932011-06-15 23:02:42 +00001366 // If this is a __weak capture, emit the release directly.
1367 } else if (isARCWeakCapture) {
1368 EmitARCDestroyWeak(srcField);
1369
John McCall6b5a61b2011-02-07 10:33:21 +00001370 // Otherwise we call _Block_object_dispose. It wouldn't be too
1371 // hard to just emit this as a cleanup if we wanted to make sure
1372 // that things were done in reverse.
1373 } else {
1374 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001375 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001376 BuildBlockRelease(value, flags);
1377 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001378 }
1379
John McCall6b5a61b2011-02-07 10:33:21 +00001380 cleanups.ForceCleanup();
1381
John McCalld16c2cf2011-02-08 08:22:06 +00001382 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001383
John McCall5936e332011-02-15 09:22:45 +00001384 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001385}
1386
John McCallf0c11f72011-03-31 08:03:29 +00001387namespace {
1388
1389/// Emits the copy/dispose helper functions for a __block object of id type.
1390class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1391 BlockFieldFlags Flags;
1392
1393public:
1394 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1395 : ByrefHelpers(alignment), Flags(flags) {}
1396
John McCall36170192011-03-31 09:19:20 +00001397 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1398 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001399 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1400
1401 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1402 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1403
1404 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1405
1406 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1407 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1408 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1409 }
1410
1411 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1412 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1413 llvm::Value *value = CGF.Builder.CreateLoad(field);
1414
1415 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1416 }
1417
1418 void profileImpl(llvm::FoldingSetNodeID &id) const {
1419 id.AddInteger(Flags.getBitMask());
1420 }
1421};
1422
John McCallf85e1932011-06-15 23:02:42 +00001423/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1424class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1425public:
1426 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1427
1428 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1429 llvm::Value *srcField) {
1430 CGF.EmitARCMoveWeak(destField, srcField);
1431 }
1432
1433 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1434 CGF.EmitARCDestroyWeak(field);
1435 }
1436
1437 void profileImpl(llvm::FoldingSetNodeID &id) const {
1438 // 0 is distinguishable from all pointers and byref flags
1439 id.AddInteger(0);
1440 }
1441};
1442
1443/// Emits the copy/dispose helpers for an ARC __block __strong variable
1444/// that's not of block-pointer type.
1445class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1446public:
1447 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1448
1449 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1450 llvm::Value *srcField) {
1451 // Do a "move" by copying the value and then zeroing out the old
1452 // variable.
1453
John McCalla59e4b72011-11-09 03:17:26 +00001454 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1455 value->setAlignment(Alignment.getQuantity());
1456
John McCallf85e1932011-06-15 23:02:42 +00001457 llvm::Value *null =
1458 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001459
1460 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1461 store->setAlignment(Alignment.getQuantity());
1462
1463 store = CGF.Builder.CreateStore(null, srcField);
1464 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001465 }
1466
1467 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCalla59e4b72011-11-09 03:17:26 +00001468 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1469 value->setAlignment(Alignment.getQuantity());
1470
John McCallf85e1932011-06-15 23:02:42 +00001471 CGF.EmitARCRelease(value, /*precise*/ false);
1472 }
1473
1474 void profileImpl(llvm::FoldingSetNodeID &id) const {
1475 // 1 is distinguishable from all pointers and byref flags
1476 id.AddInteger(1);
1477 }
1478};
1479
John McCalla59e4b72011-11-09 03:17:26 +00001480/// Emits the copy/dispose helpers for an ARC __block __strong
1481/// variable that's of block-pointer type.
1482class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1483public:
1484 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1485
1486 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1487 llvm::Value *srcField) {
1488 // Do the copy with objc_retainBlock; that's all that
1489 // _Block_object_assign would do anyway, and we'd have to pass the
1490 // right arguments to make sure it doesn't get no-op'ed.
1491 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1492 oldValue->setAlignment(Alignment.getQuantity());
1493
1494 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1495
1496 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1497 store->setAlignment(Alignment.getQuantity());
1498 }
1499
1500 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1501 llvm::LoadInst *value = CGF.Builder.CreateLoad(field);
1502 value->setAlignment(Alignment.getQuantity());
1503
1504 CGF.EmitARCRelease(value, /*precise*/ false);
1505 }
1506
1507 void profileImpl(llvm::FoldingSetNodeID &id) const {
1508 // 2 is distinguishable from all pointers and byref flags
1509 id.AddInteger(2);
1510 }
1511};
1512
John McCallf0c11f72011-03-31 08:03:29 +00001513/// Emits the copy/dispose helpers for a __block variable with a
1514/// nontrivial copy constructor or destructor.
1515class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1516 QualType VarType;
1517 const Expr *CopyExpr;
1518
1519public:
1520 CXXByrefHelpers(CharUnits alignment, QualType type,
1521 const Expr *copyExpr)
1522 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1523
1524 bool needsCopy() const { return CopyExpr != 0; }
1525 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1526 llvm::Value *srcField) {
1527 if (!CopyExpr) return;
1528 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1529 }
1530
1531 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1532 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1533 CGF.PushDestructorCleanup(VarType, field);
1534 CGF.PopCleanupBlocks(cleanupDepth);
1535 }
1536
1537 void profileImpl(llvm::FoldingSetNodeID &id) const {
1538 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1539 }
1540};
1541} // end anonymous namespace
1542
1543static llvm::Constant *
1544generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001545 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001546 CodeGenModule::ByrefHelpers &byrefInfo) {
1547 ASTContext &Context = CGF.getContext();
1548
1549 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001550
John McCalld26bc762011-03-09 04:27:21 +00001551 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001552 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001553 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001554
John McCallf0c11f72011-03-31 08:03:29 +00001555 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001556 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Mike Stump45031c02009-03-06 02:29:21 +00001558 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001559 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001560
John McCallf0c11f72011-03-31 08:03:29 +00001561 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001562 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001563
Mike Stump3899a7f2009-06-05 23:26:36 +00001564 // FIXME: We'd like to put these into a mergable by content, with
1565 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001566 llvm::Function *Fn =
1567 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001568 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001569
1570 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001571 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001572
John McCallf0c11f72011-03-31 08:03:29 +00001573 FunctionDecl *FD = FunctionDecl::Create(Context,
1574 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001575 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001576 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001577 SC_Static,
1578 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001579 false, true);
John McCallf85e1932011-06-15 23:02:42 +00001580
John McCallf0c11f72011-03-31 08:03:29 +00001581 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001582
John McCallf0c11f72011-03-31 08:03:29 +00001583 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001584 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001585
John McCallf0c11f72011-03-31 08:03:29 +00001586 // dst->x
1587 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1588 destField = CGF.Builder.CreateLoad(destField);
1589 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1590 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001591
John McCallf0c11f72011-03-31 08:03:29 +00001592 // src->x
1593 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1594 srcField = CGF.Builder.CreateLoad(srcField);
1595 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1596 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1597
1598 byrefInfo.emitCopy(CGF, destField, srcField);
1599 }
1600
1601 CGF.FinishFunction();
1602
1603 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001604}
1605
John McCallf0c11f72011-03-31 08:03:29 +00001606/// Build the copy helper for a __block variable.
1607static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001608 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001609 CodeGenModule::ByrefHelpers &info) {
1610 CodeGenFunction CGF(CGM);
1611 return generateByrefCopyHelper(CGF, byrefType, info);
1612}
1613
1614/// Generate code for a __block variable's dispose helper.
1615static llvm::Constant *
1616generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001617 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001618 CodeGenModule::ByrefHelpers &byrefInfo) {
1619 ASTContext &Context = CGF.getContext();
1620 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001621
John McCalld26bc762011-03-09 04:27:21 +00001622 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001623 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001624 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Mike Stump45031c02009-03-06 02:29:21 +00001626 const CGFunctionInfo &FI =
John McCallf0c11f72011-03-31 08:03:29 +00001627 CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001628
John McCallf0c11f72011-03-31 08:03:29 +00001629 CodeGenTypes &Types = CGF.CGM.getTypes();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001630 llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
Mike Stump45031c02009-03-06 02:29:21 +00001631
Mike Stump3899a7f2009-06-05 23:26:36 +00001632 // FIXME: We'd like to put these into a mergable by content, with
1633 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001634 llvm::Function *Fn =
1635 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001636 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001637 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001638
1639 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001640 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001641
John McCallf0c11f72011-03-31 08:03:29 +00001642 FunctionDecl *FD = FunctionDecl::Create(Context,
1643 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001644 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001645 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001646 SC_Static,
1647 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001648 false, true);
John McCallf0c11f72011-03-31 08:03:29 +00001649 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001650
John McCallf0c11f72011-03-31 08:03:29 +00001651 if (byrefInfo.needsDispose()) {
1652 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1653 V = CGF.Builder.CreateLoad(V);
1654 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1655 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001656
John McCallf0c11f72011-03-31 08:03:29 +00001657 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001658 }
Mike Stump45031c02009-03-06 02:29:21 +00001659
John McCallf0c11f72011-03-31 08:03:29 +00001660 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001661
John McCallf0c11f72011-03-31 08:03:29 +00001662 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001663}
1664
John McCallf0c11f72011-03-31 08:03:29 +00001665/// Build the dispose helper for a __block variable.
1666static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001667 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001668 CodeGenModule::ByrefHelpers &info) {
1669 CodeGenFunction CGF(CGM);
1670 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001671}
1672
John McCallf0c11f72011-03-31 08:03:29 +00001673///
1674template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001675 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001676 T &byrefInfo) {
1677 // Increase the field's alignment to be at least pointer alignment,
1678 // since the layout of the byref struct will guarantee at least that.
1679 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1680 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1681
1682 llvm::FoldingSetNodeID id;
1683 byrefInfo.Profile(id);
1684
1685 void *insertPos;
1686 CodeGenModule::ByrefHelpers *node
1687 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1688 if (node) return static_cast<T*>(node);
1689
1690 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1691 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1692
1693 T *copy = new (CGM.getContext()) T(byrefInfo);
1694 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1695 return copy;
1696}
1697
1698CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001699CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001700 const AutoVarEmission &emission) {
1701 const VarDecl &var = *emission.Variable;
1702 QualType type = var.getType();
1703
1704 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1705 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1706 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1707
1708 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1709 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1710 }
1711
John McCallf85e1932011-06-15 23:02:42 +00001712 // Otherwise, if we don't have a retainable type, there's nothing to do.
1713 // that the runtime does extra copies.
1714 if (!type->isObjCRetainableType()) return 0;
1715
1716 Qualifiers qs = type.getQualifiers();
1717
1718 // If we have lifetime, that dominates.
1719 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
1720 assert(getLangOptions().ObjCAutoRefCount);
1721
1722 switch (lifetime) {
1723 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1724
1725 // These are just bits as far as the runtime is concerned.
1726 case Qualifiers::OCL_ExplicitNone:
1727 case Qualifiers::OCL_Autoreleasing:
1728 return 0;
1729
1730 // Tell the runtime that this is ARC __weak, called by the
1731 // byref routines.
1732 case Qualifiers::OCL_Weak: {
1733 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1734 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1735 }
1736
1737 // ARC __strong __block variables need to be retained.
1738 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001739 // Block pointers need to be copied, and there's no direct
1740 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001741 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001742 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001743 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1744
1745 // Otherwise, we transfer ownership of the retain from the stack
1746 // to the heap.
1747 } else {
1748 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1749 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1750 }
1751 }
1752 llvm_unreachable("fell out of lifetime switch!");
1753 }
1754
John McCallf0c11f72011-03-31 08:03:29 +00001755 BlockFieldFlags flags;
1756 if (type->isBlockPointerType()) {
1757 flags |= BLOCK_FIELD_IS_BLOCK;
1758 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1759 type->isObjCObjectPointerType()) {
1760 flags |= BLOCK_FIELD_IS_OBJECT;
1761 } else {
1762 return 0;
1763 }
1764
1765 if (type.isObjCGCWeak())
1766 flags |= BLOCK_FIELD_IS_WEAK;
1767
1768 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1769 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001770}
1771
John McCall5af02db2011-03-31 01:59:53 +00001772unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1773 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1774
1775 return ByRefValueInfo.find(VD)->second.second;
1776}
1777
1778llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1779 const VarDecl *V) {
1780 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1781 Loc = Builder.CreateLoad(Loc);
1782 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1783 V->getNameAsString());
1784 return Loc;
1785}
1786
1787/// BuildByRefType - This routine changes a __block variable declared as T x
1788/// into:
1789///
1790/// struct {
1791/// void *__isa;
1792/// void *__forwarding;
1793/// int32_t __flags;
1794/// int32_t __size;
1795/// void *__copy_helper; // only if needed
1796/// void *__destroy_helper; // only if needed
1797/// char padding[X]; // only if needed
1798/// T x;
1799/// } x
1800///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001801llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1802 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001803 if (Info.first)
1804 return Info.first;
1805
1806 QualType Ty = D->getType();
1807
Chris Lattner5f9e2722011-07-23 10:55:15 +00001808 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001809
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001810 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001811 llvm::StructType::create(getLLVMContext(),
1812 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001813
1814 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001815 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001816
1817 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001818 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001819
1820 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001821 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001822
1823 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001824 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001825
1826 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
1827 if (HasCopyAndDispose) {
1828 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001829 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001830
1831 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001832 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001833 }
1834
1835 bool Packed = false;
1836 CharUnits Align = getContext().getDeclAlign(D);
1837 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1838 // We have to insert padding.
1839
1840 // The struct above has 2 32-bit integers.
1841 unsigned CurrentOffsetInBytes = 4 * 2;
1842
1843 // And either 2 or 4 pointers.
1844 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
1845 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
1846
1847 // Align the offset.
1848 unsigned AlignedOffsetInBytes =
1849 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1850
1851 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1852 if (NumPaddingBytes > 0) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001853 llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
John McCall5af02db2011-03-31 01:59:53 +00001854 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001855 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001856 if (NumPaddingBytes > 1)
1857 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1858
John McCall0774cb82011-05-15 01:53:33 +00001859 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001860
1861 // We want a packed struct.
1862 Packed = true;
1863 }
1864 }
1865
1866 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001867 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001868
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001869 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001870
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001871 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001872
John McCall0774cb82011-05-15 01:53:33 +00001873 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001874
1875 return Info.first;
1876}
1877
1878/// Initialize the structural components of a __block variable, i.e.
1879/// everything but the actual object.
1880void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001881 // Find the address of the local.
1882 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001883
John McCallf0c11f72011-03-31 08:03:29 +00001884 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001885 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001886 cast<llvm::PointerType>(addr->getType())->getElementType());
1887
1888 // Build the byref helpers if necessary. This is null if we don't need any.
1889 CodeGenModule::ByrefHelpers *helpers =
1890 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001891
1892 const VarDecl &D = *emission.Variable;
1893 QualType type = D.getType();
1894
John McCallf0c11f72011-03-31 08:03:29 +00001895 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001896
1897 // Initialize the 'isa', which is just 0 or 1.
1898 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001899 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001900 isa = 1;
1901 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1902 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1903
1904 // Store the address of the variable into its own forwarding pointer.
1905 Builder.CreateStore(addr,
1906 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1907
1908 // Blocks ABI:
1909 // c) the flags field is set to either 0 if no helper functions are
1910 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
1911 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00001912 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00001913 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
1914 Builder.CreateStructGEP(addr, 2, "byref.flags"));
1915
John McCallf0c11f72011-03-31 08:03:29 +00001916 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
1917 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00001918 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
1919
John McCallf0c11f72011-03-31 08:03:29 +00001920 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00001921 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00001922 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001923
1924 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00001925 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00001926 }
1927}
1928
John McCalld16c2cf2011-02-08 08:22:06 +00001929void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00001930 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001931 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00001932 V = Builder.CreateBitCast(V, Int8PtrTy);
1933 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00001934 Builder.CreateCall2(F, V, N);
1935}
John McCall5af02db2011-03-31 01:59:53 +00001936
1937namespace {
1938 struct CallBlockRelease : EHScopeStack::Cleanup {
1939 llvm::Value *Addr;
1940 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
1941
John McCallad346f42011-07-12 20:27:29 +00001942 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001943 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00001944 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
1945 }
1946 };
1947}
1948
1949/// Enter a cleanup to destroy a __block variable. Note that this
1950/// cleanup should be a no-op if the variable hasn't left the stack
1951/// yet; if a cleanup is required for the variable itself, that needs
1952/// to be done externally.
1953void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
1954 // We don't enter this cleanup if we're in pure-GC mode.
Douglas Gregore289d812011-09-13 17:21:33 +00001955 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00001956 return;
1957
1958 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1959}
John McCall13db5cf2011-09-09 20:41:01 +00001960
1961/// Adjust the declaration of something from the blocks API.
1962static void configureBlocksRuntimeObject(CodeGenModule &CGM,
1963 llvm::Constant *C) {
1964 if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
1965
1966 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
1967 if (GV->isDeclaration() &&
1968 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
1969 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1970}
1971
1972llvm::Constant *CodeGenModule::getBlockObjectDispose() {
1973 if (BlockObjectDispose)
1974 return BlockObjectDispose;
1975
1976 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
1977 llvm::FunctionType *fty
1978 = llvm::FunctionType::get(VoidTy, args, false);
1979 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
1980 configureBlocksRuntimeObject(*this, BlockObjectDispose);
1981 return BlockObjectDispose;
1982}
1983
1984llvm::Constant *CodeGenModule::getBlockObjectAssign() {
1985 if (BlockObjectAssign)
1986 return BlockObjectAssign;
1987
1988 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
1989 llvm::FunctionType *fty
1990 = llvm::FunctionType::get(VoidTy, args, false);
1991 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
1992 configureBlocksRuntimeObject(*this, BlockObjectAssign);
1993 return BlockObjectAssign;
1994}
1995
1996llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
1997 if (NSConcreteGlobalBlock)
1998 return NSConcreteGlobalBlock;
1999
2000 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2001 Int8PtrTy->getPointerTo(), 0);
2002 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2003 return NSConcreteGlobalBlock;
2004}
2005
2006llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2007 if (NSConcreteStackBlock)
2008 return NSConcreteStackBlock;
2009
2010 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2011 Int8PtrTy->getPointerTo(), 0);
2012 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2013 return NSConcreteStackBlock;
2014}