blob: 2d51a154add7dd9539ce69ae10089b5c64cca100 [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
John McCalld16c2cf2011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Module.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Fariborz Jahanian7d4b9fa2012-11-14 17:43:08 +000024#include <cstdio>
Torok Edwinf42e4a62009-08-24 13:25:12 +000025
Anders Carlssonacfde802009-02-12 00:39:25 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall1a343eb2011-11-10 08:15:53 +000029CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
30 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanianf22ae652012-11-01 18:32:55 +000031 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
32 StructureType(0), Block(block),
John McCall6f103ba2011-11-10 10:43:54 +000033 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000034
John McCall1a343eb2011-11-10 08:15:53 +000035 // Skip asm prefix, if any. 'name' is usually taken directly from
36 // the mangled name of the enclosing function.
37 if (!name.empty() && name[0] == '\01')
38 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000039}
40
John McCallf0c11f72011-03-31 08:03:29 +000041// Anchor the vtable to this translation unit.
42CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
43
John McCall6b5a61b2011-02-07 10:33:21 +000044/// Build the given block as a global block.
45static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
46 const CGBlockInfo &blockInfo,
47 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000048
John McCall6b5a61b2011-02-07 10:33:21 +000049/// Build the helper function to copy a block.
50static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
51 const CGBlockInfo &blockInfo) {
52 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
53}
54
55/// Build the helper function to dipose of a block.
56static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
57 const CGBlockInfo &blockInfo) {
58 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
59}
60
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000061/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
62/// buildBlockDescriptor is accessed from 5th field of the Block_literal
63/// meta-data and contains stationary information about the block literal.
64/// Its definition will have 4 (or optinally 6) words.
65/// struct Block_descriptor {
66/// unsigned long reserved;
67/// unsigned long size; // size of Block_literal metadata in bytes.
68/// void *copy_func_helper_decl; // optional copy helper.
69/// void *destroy_func_decl; // optioanl destructor helper.
70/// void *block_method_encoding_address;//@encode for block literal signature.
71/// void *block_layout_info; // encoding of captured block variables.
72/// };
John McCall6b5a61b2011-02-07 10:33:21 +000073static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
74 const CGBlockInfo &blockInfo) {
75 ASTContext &C = CGM.getContext();
76
Chris Lattner2acc6e32011-07-18 04:24:23 +000077 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
78 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000079
Chris Lattner5f9e2722011-07-23 10:55:15 +000080 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000081
82 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000083 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000084
85 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000086 // FIXME: What is the right way to say this doesn't fit? We should give
87 // a user diagnostic in that case. Better fix would be to change the
88 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000089 elements.push_back(llvm::ConstantInt::get(ulong,
90 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000091
John McCall6b5a61b2011-02-07 10:33:21 +000092 // Optional copy/dispose helpers.
93 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000094 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000095 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000096
97 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000098 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000099 }
100
John McCall6b5a61b2011-02-07 10:33:21 +0000101 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
102 std::string typeAtEncoding =
103 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
104 elements.push_back(llvm::ConstantExpr::getBitCast(
105 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000106
John McCall6b5a61b2011-02-07 10:33:21 +0000107 // GC layout.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000108 if (C.getLangOpts().ObjC1) {
109 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
110 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
111 else
112 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
113 }
John McCall6b5a61b2011-02-07 10:33:21 +0000114 else
115 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000116
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000117 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000118
John McCall6b5a61b2011-02-07 10:33:21 +0000119 llvm::GlobalVariable *global =
120 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
121 llvm::GlobalValue::InternalLinkage,
122 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000123
John McCall6b5a61b2011-02-07 10:33:21 +0000124 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000125}
126
John McCall6b5a61b2011-02-07 10:33:21 +0000127/*
128 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000129
John McCall6b5a61b2011-02-07 10:33:21 +0000130 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
131 struct Block_literal {
132 /// Initialized to one of:
133 /// extern void *_NSConcreteStackBlock[];
134 /// extern void *_NSConcreteGlobalBlock[];
135 ///
136 /// In theory, we could start one off malloc'ed by setting
137 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
138 /// this isa:
139 /// extern void *_NSConcreteMallocBlock[];
140 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000141
John McCall6b5a61b2011-02-07 10:33:21 +0000142 /// These are the flags (with corresponding bit number) that the
143 /// compiler is actually supposed to know about.
144 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
145 /// descriptor provides copy and dispose helper functions
146 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
147 /// object with a nontrivial destructor or copy constructor
148 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
149 /// as global memory
150 /// 29. BLOCK_USE_STRET - indicates that the block function
151 /// uses stret, which objc_msgSend needs to know about
152 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
153 /// @encoded signature string
154 /// And we're not supposed to manipulate these:
155 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
156 /// to malloc'ed memory
157 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
158 /// to GC-allocated memory
159 /// Additionally, the bottom 16 bits are a reference count which
160 /// should be zero on the stack.
161 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Reserved; should be zero-initialized.
164 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Function pointer generated from block literal.
167 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000168
John McCall6b5a61b2011-02-07 10:33:21 +0000169 /// Block description metadata generated from block literal.
170 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000171
John McCall6b5a61b2011-02-07 10:33:21 +0000172 /// Captured values follow.
173 _CapturesTypes captures...;
174 };
175 */
David Chisnall5e530af2009-11-17 19:33:30 +0000176
John McCall6b5a61b2011-02-07 10:33:21 +0000177/// The number of fields in a block header.
178const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000179
John McCall6b5a61b2011-02-07 10:33:21 +0000180namespace {
181 /// A chunk of data that we actually have to capture in the block.
182 struct BlockLayoutChunk {
183 CharUnits Alignment;
184 CharUnits Size;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000185 Qualifiers::ObjCLifetime Lifetime;
John McCall6b5a61b2011-02-07 10:33:21 +0000186 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000187 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000188
John McCall6b5a61b2011-02-07 10:33:21 +0000189 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000190 Qualifiers::ObjCLifetime lifetime,
John McCall6b5a61b2011-02-07 10:33:21 +0000191 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000192 llvm::Type *type)
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000193 : Alignment(align), Size(size), Lifetime(lifetime),
194 Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000195
John McCall6b5a61b2011-02-07 10:33:21 +0000196 /// Tell the block info that this chunk has the given field index.
197 void setIndex(CGBlockInfo &info, unsigned index) {
198 if (!Capture)
199 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000200 else
John McCall6b5a61b2011-02-07 10:33:21 +0000201 info.Captures[Capture->getVariable()]
202 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000203 }
John McCall6b5a61b2011-02-07 10:33:21 +0000204 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000205
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000206 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
207 /// all __weak together. Preserve descending alignment in all situations.
John McCall6b5a61b2011-02-07 10:33:21 +0000208 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000209 CharUnits LeftValue, RightValue;
210 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
211 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
212
213 if (left.Lifetime == Qualifiers::OCL_Strong &&
214 left.Alignment >= right.Alignment)
215 LeftValue = CharUnits::fromQuantity(64);
216 else if (LeftByref && left.Alignment >= right.Alignment)
217 LeftValue = CharUnits::fromQuantity(32);
218 else if (left.Lifetime == Qualifiers::OCL_Weak &&
219 left.Alignment >= right.Alignment)
220 LeftValue = CharUnits::fromQuantity(16);
221 else
222 LeftValue = left.Alignment;
223 if (right.Lifetime == Qualifiers::OCL_Strong &&
224 right.Alignment >= left.Alignment)
225 RightValue = CharUnits::fromQuantity(64);
226 else if (RightByref && right.Alignment >= left.Alignment)
227 RightValue = CharUnits::fromQuantity(32);
228 else if (right.Lifetime == Qualifiers::OCL_Weak &&
229 right.Alignment >= left.Alignment)
230 RightValue = CharUnits::fromQuantity(16);
231 else
232 RightValue = right.Alignment;
233
234 return LeftValue > RightValue;
John McCall6b5a61b2011-02-07 10:33:21 +0000235 }
236}
237
John McCall461c9c12011-02-08 03:07:00 +0000238/// Determines if the given type is safe for constant capture in C++.
239static bool isSafeForCXXConstantCapture(QualType type) {
240 const RecordType *recordType =
241 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
242
243 // Only records can be unsafe.
244 if (!recordType) return true;
245
246 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
247
248 // Maintain semantics for classes with non-trivial dtors or copy ctors.
249 if (!record->hasTrivialDestructor()) return false;
Richard Smith426391c2012-11-16 00:53:38 +0000250 if (record->hasNonTrivialCopyConstructor()) return false;
John McCall461c9c12011-02-08 03:07:00 +0000251
252 // Otherwise, we just have to make sure there aren't any mutable
253 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000254 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000255}
256
John McCall6b5a61b2011-02-07 10:33:21 +0000257/// It is illegal to modify a const object after initialization.
258/// Therefore, if a const object has a constant initializer, we don't
259/// actually need to keep storage for it in the block; we'll just
260/// rematerialize it at the start of the block function. This is
261/// acceptable because we make no promises about address stability of
262/// captured variables.
263static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000264 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000265 const VarDecl *var) {
266 QualType type = var->getType();
267
268 // We can only do this if the variable is const.
269 if (!type.isConstQualified()) return 0;
270
John McCall461c9c12011-02-08 03:07:00 +0000271 // Furthermore, in C++ we have to worry about mutable fields:
272 // C++ [dcl.type.cv]p4:
273 // Except that any class member declared mutable can be
274 // modified, any attempt to modify a const object during its
275 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000276 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000277 return 0;
278
279 // If the variable doesn't have any initializer (shouldn't this be
280 // invalid?), it's not clear what we should do. Maybe capture as
281 // zero?
282 const Expr *init = var->getInit();
283 if (!init) return 0;
284
Richard Smith2d6a5672012-01-14 04:30:29 +0000285 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000286}
287
288/// Get the low bit of a nonzero character count. This is the
289/// alignment of the nth byte if the 0th byte is universally aligned.
290static CharUnits getLowBit(CharUnits v) {
291 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
292}
293
294static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000295 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000296 ASTContext &C = CGM.getContext();
297
298 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
299 CharUnits ptrSize, ptrAlign, intSize, intAlign;
300 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
301 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
302
303 // Are there crazy embedded platforms where this isn't true?
304 assert(intSize <= ptrSize && "layout assumptions horribly violated");
305
306 CharUnits headerSize = ptrSize;
307 if (2 * intSize < ptrAlign) headerSize += ptrSize;
308 else headerSize += 2 * intSize;
309 headerSize += 2 * ptrSize;
310
311 info.BlockAlign = ptrAlign;
312 info.BlockSize = headerSize;
313
314 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000315 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
316 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000317 elementTypes.push_back(i8p);
318 elementTypes.push_back(intTy);
319 elementTypes.push_back(intTy);
320 elementTypes.push_back(i8p);
321 elementTypes.push_back(CGM.getBlockDescriptorType());
322
323 assert(elementTypes.size() == BlockHeaderSize);
324}
325
326/// Compute the layout of the given block. Attempts to lay the block
327/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000328static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
329 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000330 ASTContext &C = CGM.getContext();
331 const BlockDecl *block = info.getBlockDecl();
332
Chris Lattner5f9e2722011-07-23 10:55:15 +0000333 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000334 initializeForBlockHeader(CGM, info, elementTypes);
335
336 if (!block->hasCaptures()) {
337 info.StructureType =
338 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
339 info.CanBeGlobal = true;
340 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000341 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000342 else if (C.getLangOpts().ObjC1 &&
343 CGM.getLangOpts().getGC() == LangOptions::NonGC)
344 info.HasCapturedVariableLayout = true;
345
John McCall6b5a61b2011-02-07 10:33:21 +0000346 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000347 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000348 layout.reserve(block->capturesCXXThis() +
349 (block->capture_end() - block->capture_begin()));
350
351 CharUnits maxFieldAlign;
352
353 // First, 'this'.
354 if (block->capturesCXXThis()) {
355 const DeclContext *DC = block->getDeclContext();
356 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
357 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000358 QualType thisType;
359 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
360 thisType = C.getPointerType(C.getRecordType(RD));
361 else
362 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000363
Jay Foadef6de3d2011-07-11 09:56:20 +0000364 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000365 std::pair<CharUnits,CharUnits> tinfo
366 = CGM.getContext().getTypeInfoInChars(thisType);
367 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
368
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000369 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
370 Qualifiers::OCL_None,
371 0, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000372 }
373
374 // Next, all the block captures.
375 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
376 ce = block->capture_end(); ci != ce; ++ci) {
377 const VarDecl *variable = ci->getVariable();
378
379 if (ci->isByRef()) {
380 // We have to copy/dispose of the __block reference.
381 info.NeedsCopyDispose = true;
382
John McCall6b5a61b2011-02-07 10:33:21 +0000383 // Just use void* instead of a pointer to the byref type.
384 QualType byRefPtrTy = C.VoidPtrTy;
385
Jay Foadef6de3d2011-07-11 09:56:20 +0000386 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000387 std::pair<CharUnits,CharUnits> tinfo
388 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
389 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
390
391 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000392 Qualifiers::OCL_None,
John McCall6b5a61b2011-02-07 10:33:21 +0000393 &*ci, llvmType));
394 continue;
395 }
396
397 // Otherwise, build a layout chunk with the size and alignment of
398 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000399 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000400 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
401 continue;
402 }
403
John McCallf85e1932011-06-15 23:02:42 +0000404 // If we have a lifetime qualifier, honor it for capture purposes.
405 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000406 Qualifiers::ObjCLifetime lifetime =
407 variable->getType().getObjCLifetime();
408 if (lifetime) {
John McCallf85e1932011-06-15 23:02:42 +0000409 switch (lifetime) {
410 case Qualifiers::OCL_None: llvm_unreachable("impossible");
411 case Qualifiers::OCL_ExplicitNone:
412 case Qualifiers::OCL_Autoreleasing:
413 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000414
John McCallf85e1932011-06-15 23:02:42 +0000415 case Qualifiers::OCL_Strong:
416 case Qualifiers::OCL_Weak:
417 info.NeedsCopyDispose = true;
418 }
419
420 // Block pointers require copy/dispose. So do Objective-C pointers.
421 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000422 info.NeedsCopyDispose = true;
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000423 // used for mrr below.
424 lifetime = Qualifiers::OCL_Strong;
John McCall6b5a61b2011-02-07 10:33:21 +0000425
426 // So do types that require non-trivial copy construction.
427 } else if (ci->hasCopyExpr()) {
428 info.NeedsCopyDispose = true;
429 info.HasCXXObject = true;
430
431 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000432 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000433 if (const CXXRecordDecl *record =
434 variable->getType()->getAsCXXRecordDecl()) {
435 if (!record->hasTrivialDestructor()) {
436 info.HasCXXObject = true;
437 info.NeedsCopyDispose = true;
438 }
439 }
440 }
441
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000442 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000443 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000444 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000445
John McCall6b5a61b2011-02-07 10:33:21 +0000446 maxFieldAlign = std::max(maxFieldAlign, align);
447
Jay Foadef6de3d2011-07-11 09:56:20 +0000448 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000449 CGM.getTypes().ConvertTypeForMem(VT);
450
Fariborz Jahanian90a2d392013-01-17 00:25:06 +0000451 layout.push_back(BlockLayoutChunk(align, size, lifetime, &*ci, llvmType));
John McCall6b5a61b2011-02-07 10:33:21 +0000452 }
453
454 // If that was everything, we're done here.
455 if (layout.empty()) {
456 info.StructureType =
457 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
458 info.CanBeGlobal = true;
459 return;
460 }
461
462 // Sort the layout by alignment. We have to use a stable sort here
463 // to get reproducible results. There should probably be an
464 // llvm::array_pod_stable_sort.
465 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000466
467 // Needed for blocks layout info.
468 info.BlockHeaderForcedGapOffset = info.BlockSize;
469 info.BlockHeaderForcedGapSize = CharUnits::Zero();
470
John McCall6b5a61b2011-02-07 10:33:21 +0000471 CharUnits &blockSize = info.BlockSize;
472 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
473
474 // Assuming that the first byte in the header is maximally aligned,
475 // get the alignment of the first byte following the header.
476 CharUnits endAlign = getLowBit(blockSize);
477
478 // If the end of the header isn't satisfactorily aligned for the
479 // maximum thing, look for things that are okay with the header-end
480 // alignment, and keep appending them until we get something that's
481 // aligned right. This algorithm is only guaranteed optimal if
482 // that condition is satisfied at some point; otherwise we can get
483 // things like:
484 // header // next byte has alignment 4
485 // something_with_size_5; // next byte has alignment 1
486 // something_with_alignment_8;
487 // which has 7 bytes of padding, as opposed to the naive solution
488 // which might have less (?).
489 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000490 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000491 li = layout.begin() + 1, le = layout.end();
492
493 // Look for something that the header end is already
494 // satisfactorily aligned for.
495 for (; li != le && endAlign < li->Alignment; ++li)
496 ;
497
498 // If we found something that's naturally aligned for the end of
499 // the header, keep adding things...
500 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000501 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000502 for (; li != le; ++li) {
503 assert(endAlign >= li->Alignment);
504
505 li->setIndex(info, elementTypes.size());
506 elementTypes.push_back(li->Type);
507 blockSize += li->Size;
508 endAlign = getLowBit(blockSize);
509
510 // ...until we get to the alignment of the maximum field.
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000511 if (endAlign >= maxFieldAlign) {
512 if (li == first) {
513 // No user field was appended. So, a gap was added.
514 // Save total gap size for use in block layout bit map.
515 info.BlockHeaderForcedGapSize = li->Size;
516 }
John McCall6b5a61b2011-02-07 10:33:21 +0000517 break;
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000518 }
John McCall6b5a61b2011-02-07 10:33:21 +0000519 }
John McCall6b5a61b2011-02-07 10:33:21 +0000520 // Don't re-append everything we just appended.
521 layout.erase(first, li);
522 }
523 }
524
John McCall6ea48412012-04-26 21:14:42 +0000525 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000526
John McCall6b5a61b2011-02-07 10:33:21 +0000527 // At this point, we just have to add padding if the end align still
528 // isn't aligned right.
529 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000530 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
531 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000532
John McCall5936e332011-02-15 09:22:45 +0000533 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
534 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000535 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000536 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000537 }
538
John McCall6c803f72012-05-01 20:28:00 +0000539 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000540 assert(endAlign == getLowBit(blockSize));
John McCall6b5a61b2011-02-07 10:33:21 +0000541 // Slam everything else on now. This works because they have
542 // strictly decreasing alignment and we expect that size is always a
543 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000544 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000545 li = layout.begin(), le = layout.end(); li != le; ++li) {
546 assert(endAlign >= li->Alignment);
547 li->setIndex(info, elementTypes.size());
548 elementTypes.push_back(li->Type);
549 blockSize += li->Size;
550 endAlign = getLowBit(blockSize);
551 }
552
553 info.StructureType =
554 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
555}
556
John McCall1a343eb2011-11-10 08:15:53 +0000557/// Enter the scope of a block. This should be run at the entrance to
558/// a full-expression so that the block's cleanups are pushed at the
559/// right place in the stack.
560static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000561 assert(CGF.HaveInsertPoint());
562
John McCall1a343eb2011-11-10 08:15:53 +0000563 // Allocate the block info and place it at the head of the list.
564 CGBlockInfo &blockInfo =
565 *new CGBlockInfo(block, CGF.CurFn->getName());
566 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
567 CGF.FirstBlockInfo = &blockInfo;
568
569 // Compute information about the layout, etc., of this block,
570 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000571 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000572
573 // Nothing else to do if it can be global.
574 if (blockInfo.CanBeGlobal) return;
575
576 // Make the allocation for the block.
577 blockInfo.Address =
578 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
579 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
580
581 // If there are cleanups to emit, enter them (but inactive).
582 if (!blockInfo.NeedsCopyDispose) return;
583
584 // Walk through the captures (in order) and find the ones not
585 // captured by constant.
586 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
587 ce = block->capture_end(); ci != ce; ++ci) {
588 // Ignore __block captures; there's nothing special in the
589 // on-stack block that we need to do for them.
590 if (ci->isByRef()) continue;
591
592 // Ignore variables that are constant-captured.
593 const VarDecl *variable = ci->getVariable();
594 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
595 if (capture.isConstant()) continue;
596
597 // Ignore objects that aren't destructed.
598 QualType::DestructionKind dtorKind =
599 variable->getType().isDestructedType();
600 if (dtorKind == QualType::DK_none) continue;
601
602 CodeGenFunction::Destroyer *destroyer;
603
604 // Block captures count as local values and have imprecise semantics.
605 // They also can't be arrays, so need to worry about that.
606 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000607 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000608 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000609 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000610 }
611
612 // GEP down to the address.
613 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
614 capture.getIndex());
615
John McCall6f103ba2011-11-10 10:43:54 +0000616 // We can use that GEP as the dominating IP.
617 if (!blockInfo.DominatingIP)
618 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
619
John McCall1a343eb2011-11-10 08:15:53 +0000620 CleanupKind cleanupKind = InactiveNormalCleanup;
621 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
622 if (useArrayEHCleanup)
623 cleanupKind = InactiveNormalAndEHCleanup;
624
625 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000626 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000627
628 // Remember where that cleanup was.
629 capture.setCleanup(CGF.EHStack.stable_begin());
630 }
631}
632
633/// Enter a full-expression with a non-trivial number of objects to
634/// clean up. This is in this file because, at the moment, the only
635/// kind of cleanup object is a BlockDecl*.
636void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
637 assert(E->getNumObjects() != 0);
638 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
639 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
640 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
641 enterBlockScope(*this, *i);
642 }
643}
644
645/// Find the layout for the given block in a linked list and remove it.
646static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
647 const BlockDecl *block) {
648 while (true) {
649 assert(head && *head);
650 CGBlockInfo *cur = *head;
651
652 // If this is the block we're looking for, splice it out of the list.
653 if (cur->getBlockDecl() == block) {
654 *head = cur->NextBlockInfo;
655 return cur;
656 }
657
658 head = &cur->NextBlockInfo;
659 }
660}
661
662/// Destroy a chain of block layouts.
663void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
664 assert(head && "destroying an empty chain");
665 do {
666 CGBlockInfo *cur = head;
667 head = cur->NextBlockInfo;
668 delete cur;
669 } while (head != 0);
670}
671
John McCall6b5a61b2011-02-07 10:33:21 +0000672/// Emit a block literal expression in the current function.
673llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000674 // If the block has no captures, we won't have a pre-computed
675 // layout for it.
676 if (!blockExpr->getBlockDecl()->hasCaptures()) {
677 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000678 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000679 blockInfo.BlockExpression = blockExpr;
680 return EmitBlockLiteral(blockInfo);
681 }
John McCall6b5a61b2011-02-07 10:33:21 +0000682
John McCall1a343eb2011-11-10 08:15:53 +0000683 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000684 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000685 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
686 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000687
John McCall1a343eb2011-11-10 08:15:53 +0000688 blockInfo->BlockExpression = blockExpr;
689 return EmitBlockLiteral(*blockInfo);
690}
691
692llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
693 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000694 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000695 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000696 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000697 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000698 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000699 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000700
701 // If there is nothing to capture, we can emit this as a global block.
702 if (blockInfo.CanBeGlobal)
703 return buildGlobalBlock(CGM, blockInfo, blockFn);
704
705 // Otherwise, we have to emit this as a local block.
706
707 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000708 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000709
710 // Build the block descriptor.
711 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
712
John McCall1a343eb2011-11-10 08:15:53 +0000713 llvm::AllocaInst *blockAddr = blockInfo.Address;
714 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000715
716 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000717 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000718 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000719 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
720 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000721 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000722
723 // Initialize the block literal.
724 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000725 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000726 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000727 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000728 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
729 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
730 "block.invoke"));
731 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
732 "block.descriptor"));
733
734 // Finally, capture all the values into the block.
735 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
736
737 // First, 'this'.
738 if (blockDecl->capturesCXXThis()) {
739 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
740 blockInfo.CXXThisIndex,
741 "block.captured-this.addr");
742 Builder.CreateStore(LoadCXXThis(), addr);
743 }
744
745 // Next, captured variables.
746 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
747 ce = blockDecl->capture_end(); ci != ce; ++ci) {
748 const VarDecl *variable = ci->getVariable();
749 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
750
751 // Ignore constant captures.
752 if (capture.isConstant()) continue;
753
754 QualType type = variable->getType();
755
756 // This will be a [[type]]*, except that a byref entry will just be
757 // an i8**.
758 llvm::Value *blockField =
759 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
760 "block.captured");
761
762 // Compute the address of the thing we're going to move into the
763 // block literal.
764 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000765 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000766 // We need to use the capture from the enclosing block.
767 const CGBlockInfo::Capture &enclosingCapture =
768 BlockInfo->getCapture(variable);
769
770 // This is a [[type]]*, except that a byref entry wil just be an i8**.
771 src = Builder.CreateStructGEP(LoadBlockStruct(),
772 enclosingCapture.getIndex(),
773 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000774 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000775 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000776 // special; we'll simply emit it directly.
777 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000778 } else {
779 // This is a [[type]]*.
780 src = LocalDeclMap[variable];
781 }
782
783 // For byrefs, we just write the pointer to the byref struct into
784 // the block field. There's no need to chase the forwarding
785 // pointer at this point, since we're building something that will
786 // live a shorter life than the stack byref anyway.
787 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000788 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000789 if (ci->isNested())
790 src = Builder.CreateLoad(src, "byref.capture");
791 else
John McCall5936e332011-02-15 09:22:45 +0000792 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000793
John McCall5936e332011-02-15 09:22:45 +0000794 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000795 Builder.CreateStore(src, blockField);
796
797 // If we have a copy constructor, evaluate that into the block field.
798 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000799 if (blockDecl->isConversionFromLambda()) {
800 // If we have a lambda conversion, emit the expression
801 // directly into the block instead.
802 CharUnits Align = getContext().getTypeAlignInChars(type);
803 AggValueSlot Slot =
804 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
805 AggValueSlot::IsDestructed,
806 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000807 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000808 EmitAggExpr(copyExpr, Slot);
809 } else {
810 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
811 }
John McCall6b5a61b2011-02-07 10:33:21 +0000812
813 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000814 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000815 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
816
817 // Otherwise, fake up a POD copy into the block field.
818 } else {
John McCallf85e1932011-06-15 23:02:42 +0000819 // Fake up a new variable so that EmitScalarInit doesn't think
820 // we're referring to the variable in its own initializer.
821 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000822 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000823
John McCallbb699b02011-02-07 18:37:40 +0000824 // We use one of these or the other depending on whether the
825 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000826 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
827 /*refersToEnclosing*/ ci->isNested(), type,
828 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000829
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000830 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000831 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000832 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000833 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000834 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000835 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000836 }
837
John McCall1a343eb2011-11-10 08:15:53 +0000838 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000839 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000840 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
841 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000842 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000843 }
John McCall6b5a61b2011-02-07 10:33:21 +0000844 }
845
846 // Cast to the converted block-pointer type, which happens (somewhat
847 // unfortunately) to be a pointer to function type.
848 llvm::Value *result =
849 Builder.CreateBitCast(blockAddr,
850 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000851
John McCall6b5a61b2011-02-07 10:33:21 +0000852 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000853}
854
855
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000856llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000857 if (BlockDescriptorType)
858 return BlockDescriptorType;
859
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000860 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000861 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000862
Mike Stumpab695142009-02-13 15:16:56 +0000863 // struct __block_descriptor {
864 // unsigned long reserved;
865 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000866 //
867 // // later, the following will be added
868 //
869 // struct {
870 // void (*copyHelper)();
871 // void (*copyHelper)();
872 // } helpers; // !!! optional
873 //
874 // const char *signature; // the block signature
875 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000876 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000877 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000878 llvm::StructType::create("struct.__block_descriptor",
879 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000880
John McCall6b5a61b2011-02-07 10:33:21 +0000881 // Now form a pointer to that.
882 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000883 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000884}
885
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000886llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000887 if (GenericBlockLiteralType)
888 return GenericBlockLiteralType;
889
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000890 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000891
Mike Stump9b8a7972009-02-13 15:25:34 +0000892 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000893 // void *__isa;
894 // int __flags;
895 // int __reserved;
896 // void (*__invoke)(void *);
897 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000898 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000899 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000900 llvm::StructType::create("struct.__block_literal_generic",
901 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
902 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000903
Mike Stump9b8a7972009-02-13 15:25:34 +0000904 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000905}
906
Mike Stumpbd65cac2009-02-19 01:01:04 +0000907
Anders Carlssona1736c02009-12-24 21:13:40 +0000908RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
909 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000910 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000911 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000912
Anders Carlssonacfde802009-02-12 00:39:25 +0000913 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
914
915 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000916 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000917 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000918
919 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000920 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000921 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
922
923 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000924 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000925
Benjamin Kramer578faa82011-09-27 21:06:10 +0000926 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000927
Anders Carlssonacfde802009-02-12 00:39:25 +0000928 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000929 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000930 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000931
Anders Carlsson782f3972009-04-08 23:13:16 +0000932 QualType FnType = BPT->getPointeeType();
933
Anders Carlssonacfde802009-02-12 00:39:25 +0000934 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000935 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000936 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000937
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000938 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000939 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000940
John McCall64cd2322011-03-09 08:39:33 +0000941 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000942 const CGFunctionInfo &FnInfo =
John McCalle56bb362012-12-07 07:03:17 +0000943 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000945 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000946 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner2acc6e32011-07-18 04:24:23 +0000948 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000949 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Anders Carlssonacfde802009-02-12 00:39:25 +0000951 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000952 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000953}
Anders Carlssond5cab542009-02-12 17:55:02 +0000954
John McCall6b5a61b2011-02-07 10:33:21 +0000955llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
956 bool isByRef) {
957 assert(BlockInfo && "evaluating block ref without block information?");
958 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000959
John McCall6b5a61b2011-02-07 10:33:21 +0000960 // Handle constant captures.
961 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000962
John McCall6b5a61b2011-02-07 10:33:21 +0000963 llvm::Value *addr =
964 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
965 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000966
John McCall6b5a61b2011-02-07 10:33:21 +0000967 if (isByRef) {
968 // addr should be a void** right now. Load, then cast the result
969 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000970
John McCall6b5a61b2011-02-07 10:33:21 +0000971 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000972 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000973 = llvm::PointerType::get(BuildByRefType(variable), 0);
974 addr = Builder.CreateBitCast(addr, byrefPointerType,
975 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000976
John McCall6b5a61b2011-02-07 10:33:21 +0000977 // Follow the forwarding pointer.
978 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
979 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000980
John McCall6b5a61b2011-02-07 10:33:21 +0000981 // Cast back to byref* and GEP over to the actual object.
982 addr = Builder.CreateBitCast(addr, byrefPointerType);
983 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
984 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000985 }
986
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000987 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000988 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000989
John McCall6b5a61b2011-02-07 10:33:21 +0000990 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000991}
992
Mike Stump67a64482009-02-14 22:16:35 +0000993llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000994CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000995 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000996 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
997 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000998
John McCall6b5a61b2011-02-07 10:33:21 +0000999 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +00001000 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001001
John McCall6b5a61b2011-02-07 10:33:21 +00001002 // Using that metadata, generate the actual block function.
1003 llvm::Constant *blockFn;
1004 {
1005 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +00001006 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1007 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +00001008 0, LocalDeclMap,
1009 false);
John McCall6b5a61b2011-02-07 10:33:21 +00001010 }
John McCall5936e332011-02-15 09:22:45 +00001011 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +00001012
John McCalld16c2cf2011-02-08 08:22:06 +00001013 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +00001014}
1015
John McCall6b5a61b2011-02-07 10:33:21 +00001016static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1017 const CGBlockInfo &blockInfo,
1018 llvm::Constant *blockFn) {
1019 assert(blockInfo.CanBeGlobal);
1020
1021 // Generate the constants for the block literal initializer.
1022 llvm::Constant *fields[BlockHeaderSize];
1023
1024 // isa
1025 fields[0] = CGM.getNSConcreteGlobalBlock();
1026
1027 // __flags
John McCall64cd2322011-03-09 08:39:33 +00001028 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1029 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1030
John McCall5936e332011-02-15 09:22:45 +00001031 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +00001032
1033 // Reserved
John McCall5936e332011-02-15 09:22:45 +00001034 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001035
1036 // Function
1037 fields[3] = blockFn;
1038
1039 // Descriptor
1040 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1041
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001042 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001043
1044 llvm::GlobalVariable *literal =
1045 new llvm::GlobalVariable(CGM.getModule(),
1046 init->getType(),
1047 /*constant*/ true,
1048 llvm::GlobalVariable::InternalLinkage,
1049 init,
1050 "__block_literal_global");
1051 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1052
1053 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001054 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001055 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1056 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001057}
1058
Mike Stump00470a12009-03-05 08:32:30 +00001059llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001060CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1061 const CGBlockInfo &blockInfo,
1062 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001063 const DeclMapTy &ldm,
1064 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001065 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001066
Devang Patel6d1155b2011-03-07 21:53:18 +00001067 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001068 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001069 CurGD = GD;
1070
John McCall6b5a61b2011-02-07 10:33:21 +00001071 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Mike Stump7f28a9c2009-03-13 23:34:28 +00001073 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001074 // to be local to this function as well, in case they're directly
1075 // referenced in a block.
1076 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1077 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1078 if (var && !var->hasLocalStorage())
1079 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001080 }
1081
John McCall6b5a61b2011-02-07 10:33:21 +00001082 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001083
John McCall6b5a61b2011-02-07 10:33:21 +00001084 // Build the argument list.
1085 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001086
John McCall6b5a61b2011-02-07 10:33:21 +00001087 // The first argument is the block pointer. Just take it as a void*
1088 // and cast it later.
1089 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001090 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001091
John McCall8178df32011-02-22 22:38:33 +00001092 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1093 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001094 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001095
John McCall6b5a61b2011-02-07 10:33:21 +00001096 // Now add the rest of the parameters.
1097 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1098 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001099 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001100
John McCall6b5a61b2011-02-07 10:33:21 +00001101 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001102 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001103 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001104 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1105 fnType->getExtInfo(),
1106 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001107 if (CGM.ReturnTypeUsesSRet(fnInfo))
1108 blockInfo.UsesStret = true;
1109
John McCallde5d3c72012-02-17 03:33:10 +00001110 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001111
John McCall6b5a61b2011-02-07 10:33:21 +00001112 MangleBuffer name;
1113 CGM.getBlockMangledName(GD, name, blockDecl);
1114 llvm::Function *fn =
1115 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1116 name.getString(), &CGM.getModule());
1117 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001118
John McCall6b5a61b2011-02-07 10:33:21 +00001119 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001120 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001121 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001122 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001123
John McCall8178df32011-02-22 22:38:33 +00001124 // Okay. Undo some of what StartFunction did.
1125
1126 // Pull the 'self' reference out of the local decl map.
1127 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1128 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001129 BlockPointer = Builder.CreateBitCast(blockAddr,
1130 blockInfo.StructureType->getPointerTo(),
1131 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001132
John McCallea1471e2010-05-20 01:18:31 +00001133 // If we have a C++ 'this' reference, go ahead and force it into
1134 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001135 if (blockDecl->capturesCXXThis()) {
1136 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1137 blockInfo.CXXThisIndex,
1138 "block.captured-this");
1139 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001140 }
1141
John McCall6b5a61b2011-02-07 10:33:21 +00001142 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1143 // appease it.
1144 if (const ObjCMethodDecl *method
1145 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1146 const VarDecl *self = method->getSelfDecl();
1147
1148 // There might not be a capture for 'self', but if there is...
1149 if (blockInfo.Captures.count(self)) {
1150 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1151 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1152 capture.getIndex(),
1153 "block.captured-self");
1154 LocalDeclMap[self] = selfAddr;
1155 }
1156 }
1157
1158 // Also force all the constant captures.
1159 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1160 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1161 const VarDecl *variable = ci->getVariable();
1162 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1163 if (!capture.isConstant()) continue;
1164
1165 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1166
1167 llvm::AllocaInst *alloca =
1168 CreateMemTemp(variable->getType(), "block.captured-const");
1169 alloca->setAlignment(align);
1170
1171 Builder.CreateStore(capture.getConstant(), alloca, align);
1172
1173 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001174 }
1175
John McCallf4b88a42012-03-10 09:33:50 +00001176 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001177 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1178 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1179 --entry_ptr;
1180
Eli Friedman64bee652012-02-25 02:48:22 +00001181 if (IsLambdaConversionToBlock)
1182 EmitLambdaBlockInvokeBody();
1183 else
1184 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001185
Mike Stumpde8c5c72009-10-01 00:27:30 +00001186 // Remember where we were...
1187 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001188
Mike Stumpde8c5c72009-10-01 00:27:30 +00001189 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001190 ++entry_ptr;
1191 Builder.SetInsertPoint(entry, entry_ptr);
1192
John McCallf4b88a42012-03-10 09:33:50 +00001193 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001194 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001195 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001196 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1197 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1198 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001199 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001200
Douglas Gregor4cdad312012-10-23 20:05:01 +00001201 if (CGM.getCodeGenOpts().getDebugInfo()
1202 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001203 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1204 if (capture.isConstant()) {
1205 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1206 Builder);
1207 continue;
1208 }
John McCall6b5a61b2011-02-07 10:33:21 +00001209
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001210 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1211 Builder, blockInfo);
1212 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001213 }
Manman Ren3c7a0e12013-01-04 18:51:35 +00001214 // Recover location if it was changed in the above loop.
1215 DI->EmitLocation(Builder,
1216 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stumpb1a6e682009-09-30 02:43:10 +00001217 }
John McCall6b5a61b2011-02-07 10:33:21 +00001218
Mike Stumpde8c5c72009-10-01 00:27:30 +00001219 // And resume where we left off.
1220 if (resume == 0)
1221 Builder.ClearInsertionPoint();
1222 else
1223 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001224
John McCall6b5a61b2011-02-07 10:33:21 +00001225 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001226
John McCall6b5a61b2011-02-07 10:33:21 +00001227 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001228}
Mike Stumpa99038c2009-02-28 09:07:16 +00001229
John McCall6b5a61b2011-02-07 10:33:21 +00001230/*
1231 notes.push_back(HelperInfo());
1232 HelperInfo &note = notes.back();
1233 note.index = capture.getIndex();
1234 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1235 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001236
John McCall6b5a61b2011-02-07 10:33:21 +00001237 if (ci->isByRef()) {
1238 note.flag = BLOCK_FIELD_IS_BYREF;
1239 if (type.isObjCGCWeak())
1240 note.flag |= BLOCK_FIELD_IS_WEAK;
1241 } else if (type->isBlockPointerType()) {
1242 note.flag = BLOCK_FIELD_IS_BLOCK;
1243 } else {
1244 note.flag = BLOCK_FIELD_IS_OBJECT;
1245 }
1246 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001247
Mike Stump00470a12009-03-05 08:32:30 +00001248
John McCallb62faef2013-01-22 03:56:22 +00001249/// Generate the copy-helper function for a block closure object:
1250/// static void block_copy_helper(block_t *dst, block_t *src);
1251/// The runtime will have previously initialized 'dst' by doing a
1252/// bit-copy of 'src'.
1253///
1254/// Note that this copies an entire block closure object to the heap;
1255/// it should not be confused with a 'byref copy helper', which moves
1256/// the contents of an individual __block variable to the heap.
John McCall6b5a61b2011-02-07 10:33:21 +00001257llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001258CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001259 ASTContext &C = getContext();
1260
1261 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001262 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1263 args.push_back(&dstDecl);
1264 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1265 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Mike Stumpa4f668f2009-03-06 01:33:24 +00001267 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001268 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1269 FunctionType::ExtInfo(),
1270 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001271
John McCall6b5a61b2011-02-07 10:33:21 +00001272 // FIXME: it would be nice if these were mergeable with things with
1273 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001274 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001275
1276 llvm::Function *Fn =
1277 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001278 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001279
1280 IdentifierInfo *II
1281 = &CGM.getContext().Idents.get("__copy_helper_block_");
1282
Devang Patel58dc5ca2011-05-02 20:37:08 +00001283 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001284 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001285
John McCall6b5a61b2011-02-07 10:33:21 +00001286 FunctionDecl *FD = FunctionDecl::Create(C,
1287 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001288 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001289 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001290 SC_Static,
1291 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001292 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001293 false);
John McCalld26bc762011-03-09 04:27:21 +00001294 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001295
Chris Lattner2acc6e32011-07-18 04:24:23 +00001296 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001297
John McCalld26bc762011-03-09 04:27:21 +00001298 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001299 src = Builder.CreateLoad(src);
1300 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001301
John McCalld26bc762011-03-09 04:27:21 +00001302 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001303 dst = Builder.CreateLoad(dst);
1304 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001305
John McCall6b5a61b2011-02-07 10:33:21 +00001306 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001307
John McCall6b5a61b2011-02-07 10:33:21 +00001308 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1309 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1310 const VarDecl *variable = ci->getVariable();
1311 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001312
John McCall6b5a61b2011-02-07 10:33:21 +00001313 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1314 if (capture.isConstant()) continue;
1315
1316 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001317 BlockFieldFlags flags;
1318
John McCall015f33b2012-10-17 02:28:37 +00001319 bool useARCWeakCopy = false;
1320 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001321
1322 if (copyExpr) {
1323 assert(!ci->isByRef());
1324 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001325
John McCall6b5a61b2011-02-07 10:33:21 +00001326 } else if (ci->isByRef()) {
1327 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001328 if (type.isObjCGCWeak())
1329 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001330
John McCallf85e1932011-06-15 23:02:42 +00001331 } else if (type->isObjCRetainableType()) {
1332 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001333 bool isBlockPointer = type->isBlockPointerType();
1334 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001335 flags = BLOCK_FIELD_IS_BLOCK;
1336
1337 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001338 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001339 Qualifiers qs = type.getQualifiers();
1340
John McCall015f33b2012-10-17 02:28:37 +00001341 // We need to register __weak direct captures with the runtime.
1342 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1343 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001344
John McCall015f33b2012-10-17 02:28:37 +00001345 // We need to retain the copied value for __strong direct captures.
1346 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1347 // If it's a block pointer, we have to copy the block and
1348 // assign that to the destination pointer, so we might as
1349 // well use _Block_object_assign. Otherwise we can avoid that.
1350 if (!isBlockPointer)
1351 useARCStrongCopy = true;
1352
1353 // Otherwise the memcpy is fine.
1354 } else {
1355 continue;
1356 }
1357
1358 // Non-ARC captures of retainable pointers are strong and
1359 // therefore require a call to _Block_object_assign.
1360 } else {
1361 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001362 }
1363 } else {
1364 continue;
1365 }
John McCall6b5a61b2011-02-07 10:33:21 +00001366
1367 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001368 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1369 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001370
1371 // If there's an explicit copy expression, we do that.
1372 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001373 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001374 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001375 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001376 } else {
1377 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001378 if (useARCStrongCopy) {
1379 // At -O0, store null into the destination field (so that the
1380 // storeStrong doesn't over-release) and then call storeStrong.
1381 // This is a workaround to not having an initStrong call.
1382 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1383 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1384 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1385 Builder.CreateStore(null, dstField);
1386 EmitARCStoreStrongCall(dstField, srcValue, true);
1387
1388 // With optimization enabled, take advantage of the fact that
1389 // the blocks runtime guarantees a memcpy of the block data, and
1390 // just emit a retain of the src field.
1391 } else {
1392 EmitARCRetainNonBlock(srcValue);
1393
1394 // We don't need this anymore, so kill it. It's not quite
1395 // worth the annoyance to avoid creating it in the first place.
1396 cast<llvm::Instruction>(dstField)->eraseFromParent();
1397 }
1398 } else {
1399 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1400 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1401 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1402 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1403 }
Mike Stump08920992009-03-07 02:35:30 +00001404 }
1405 }
1406
John McCalld16c2cf2011-02-08 08:22:06 +00001407 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001408
John McCall5936e332011-02-15 09:22:45 +00001409 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001410}
1411
John McCallb62faef2013-01-22 03:56:22 +00001412/// Generate the destroy-helper function for a block closure object:
1413/// static void block_destroy_helper(block_t *theBlock);
1414///
1415/// Note that this destroys a heap-allocated block closure object;
1416/// it should not be confused with a 'byref destroy helper', which
1417/// destroys the heap-allocated contents of an individual __block
1418/// variable.
John McCall6b5a61b2011-02-07 10:33:21 +00001419llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001420CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001421 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001422
John McCall6b5a61b2011-02-07 10:33:21 +00001423 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001424 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1425 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Mike Stumpa4f668f2009-03-06 01:33:24 +00001427 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001428 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1429 FunctionType::ExtInfo(),
1430 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001431
Mike Stump3899a7f2009-06-05 23:26:36 +00001432 // FIXME: We'd like to put these into a mergable by content, with
1433 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001434 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001435
1436 llvm::Function *Fn =
1437 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001438 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001439
Devang Patel58dc5ca2011-05-02 20:37:08 +00001440 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001441 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001442
Mike Stumpa4f668f2009-03-06 01:33:24 +00001443 IdentifierInfo *II
1444 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1445
John McCall6b5a61b2011-02-07 10:33:21 +00001446 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001447 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001448 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001449 SC_Static,
1450 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001451 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001452 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001453
Chris Lattner2acc6e32011-07-18 04:24:23 +00001454 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001455
John McCalld26bc762011-03-09 04:27:21 +00001456 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001457 src = Builder.CreateLoad(src);
1458 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001459
John McCall6b5a61b2011-02-07 10:33:21 +00001460 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1461
John McCalld16c2cf2011-02-08 08:22:06 +00001462 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001463
1464 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1465 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1466 const VarDecl *variable = ci->getVariable();
1467 QualType type = variable->getType();
1468
1469 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1470 if (capture.isConstant()) continue;
1471
John McCalld16c2cf2011-02-08 08:22:06 +00001472 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001473 const CXXDestructorDecl *dtor = 0;
1474
John McCall015f33b2012-10-17 02:28:37 +00001475 bool useARCWeakDestroy = false;
1476 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001477
John McCall6b5a61b2011-02-07 10:33:21 +00001478 if (ci->isByRef()) {
1479 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001480 if (type.isObjCGCWeak())
1481 flags |= BLOCK_FIELD_IS_WEAK;
1482 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1483 if (record->hasTrivialDestructor())
1484 continue;
1485 dtor = record->getDestructor();
1486 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001487 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001488 if (type->isBlockPointerType())
1489 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001490
John McCallf85e1932011-06-15 23:02:42 +00001491 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001492 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001493 Qualifiers qs = type.getQualifiers();
1494
1495 // Don't generate special dispose logic for a captured object
1496 // unless it's __strong or __weak.
1497 if (!qs.hasStrongOrWeakObjCLifetime())
1498 continue;
1499
1500 // Support __weak direct captures.
1501 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001502 useARCWeakDestroy = true;
1503
1504 // Tools really want us to use objc_storeStrong here.
1505 else
1506 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001507 }
1508 } else {
1509 continue;
1510 }
John McCall6b5a61b2011-02-07 10:33:21 +00001511
1512 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001513 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001514
1515 // If there's an explicit copy expression, we do that.
1516 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001517 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001518
John McCallf85e1932011-06-15 23:02:42 +00001519 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001520 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001521 EmitARCDestroyWeak(srcField);
1522
John McCall015f33b2012-10-17 02:28:37 +00001523 // Destroy strong objects with a call if requested.
1524 } else if (useARCStrongDestroy) {
1525 EmitARCDestroyStrong(srcField, /*precise*/ false);
1526
John McCall6b5a61b2011-02-07 10:33:21 +00001527 // Otherwise we call _Block_object_dispose. It wouldn't be too
1528 // hard to just emit this as a cleanup if we wanted to make sure
1529 // that things were done in reverse.
1530 } else {
1531 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001532 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001533 BuildBlockRelease(value, flags);
1534 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001535 }
1536
John McCall6b5a61b2011-02-07 10:33:21 +00001537 cleanups.ForceCleanup();
1538
John McCalld16c2cf2011-02-08 08:22:06 +00001539 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001540
John McCall5936e332011-02-15 09:22:45 +00001541 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001542}
1543
John McCallf0c11f72011-03-31 08:03:29 +00001544namespace {
1545
1546/// Emits the copy/dispose helper functions for a __block object of id type.
1547class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1548 BlockFieldFlags Flags;
1549
1550public:
1551 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1552 : ByrefHelpers(alignment), Flags(flags) {}
1553
John McCall36170192011-03-31 09:19:20 +00001554 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1555 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001556 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1557
1558 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1559 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1560
1561 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1562
1563 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1564 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1565 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1566 }
1567
1568 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1569 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1570 llvm::Value *value = CGF.Builder.CreateLoad(field);
1571
1572 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1573 }
1574
1575 void profileImpl(llvm::FoldingSetNodeID &id) const {
1576 id.AddInteger(Flags.getBitMask());
1577 }
1578};
1579
John McCallf85e1932011-06-15 23:02:42 +00001580/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1581class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1582public:
1583 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1584
1585 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1586 llvm::Value *srcField) {
1587 CGF.EmitARCMoveWeak(destField, srcField);
1588 }
1589
1590 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1591 CGF.EmitARCDestroyWeak(field);
1592 }
1593
1594 void profileImpl(llvm::FoldingSetNodeID &id) const {
1595 // 0 is distinguishable from all pointers and byref flags
1596 id.AddInteger(0);
1597 }
1598};
1599
1600/// Emits the copy/dispose helpers for an ARC __block __strong variable
1601/// that's not of block-pointer type.
1602class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1603public:
1604 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1605
1606 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1607 llvm::Value *srcField) {
1608 // Do a "move" by copying the value and then zeroing out the old
1609 // variable.
1610
John McCalla59e4b72011-11-09 03:17:26 +00001611 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1612 value->setAlignment(Alignment.getQuantity());
1613
John McCallf85e1932011-06-15 23:02:42 +00001614 llvm::Value *null =
1615 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001616
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001617 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahanianba3c9ca2013-01-05 00:32:13 +00001618 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1619 store->setAlignment(Alignment.getQuantity());
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001620 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1621 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1622 return;
1623 }
John McCalla59e4b72011-11-09 03:17:26 +00001624 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1625 store->setAlignment(Alignment.getQuantity());
1626
1627 store = CGF.Builder.CreateStore(null, srcField);
1628 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001629 }
1630
1631 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001632 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001633 }
1634
1635 void profileImpl(llvm::FoldingSetNodeID &id) const {
1636 // 1 is distinguishable from all pointers and byref flags
1637 id.AddInteger(1);
1638 }
1639};
1640
John McCalla59e4b72011-11-09 03:17:26 +00001641/// Emits the copy/dispose helpers for an ARC __block __strong
1642/// variable that's of block-pointer type.
1643class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1644public:
1645 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1646
1647 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1648 llvm::Value *srcField) {
1649 // Do the copy with objc_retainBlock; that's all that
1650 // _Block_object_assign would do anyway, and we'd have to pass the
1651 // right arguments to make sure it doesn't get no-op'ed.
1652 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1653 oldValue->setAlignment(Alignment.getQuantity());
1654
1655 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1656
1657 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1658 store->setAlignment(Alignment.getQuantity());
1659 }
1660
1661 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001662 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001663 }
1664
1665 void profileImpl(llvm::FoldingSetNodeID &id) const {
1666 // 2 is distinguishable from all pointers and byref flags
1667 id.AddInteger(2);
1668 }
1669};
1670
John McCallf0c11f72011-03-31 08:03:29 +00001671/// Emits the copy/dispose helpers for a __block variable with a
1672/// nontrivial copy constructor or destructor.
1673class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1674 QualType VarType;
1675 const Expr *CopyExpr;
1676
1677public:
1678 CXXByrefHelpers(CharUnits alignment, QualType type,
1679 const Expr *copyExpr)
1680 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1681
1682 bool needsCopy() const { return CopyExpr != 0; }
1683 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1684 llvm::Value *srcField) {
1685 if (!CopyExpr) return;
1686 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1687 }
1688
1689 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1690 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1691 CGF.PushDestructorCleanup(VarType, field);
1692 CGF.PopCleanupBlocks(cleanupDepth);
1693 }
1694
1695 void profileImpl(llvm::FoldingSetNodeID &id) const {
1696 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1697 }
1698};
1699} // end anonymous namespace
1700
1701static llvm::Constant *
1702generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001703 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001704 unsigned valueFieldIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001705 CodeGenModule::ByrefHelpers &byrefInfo) {
1706 ASTContext &Context = CGF.getContext();
1707
1708 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001709
John McCalld26bc762011-03-09 04:27:21 +00001710 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001711 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001712 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001713
John McCallf0c11f72011-03-31 08:03:29 +00001714 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001715 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Mike Stump45031c02009-03-06 02:29:21 +00001717 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001718 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1719 FunctionType::ExtInfo(),
1720 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001721
John McCallf0c11f72011-03-31 08:03:29 +00001722 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001723 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001724
Mike Stump3899a7f2009-06-05 23:26:36 +00001725 // FIXME: We'd like to put these into a mergable by content, with
1726 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001727 llvm::Function *Fn =
1728 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001729 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001730
1731 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001732 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001733
John McCallf0c11f72011-03-31 08:03:29 +00001734 FunctionDecl *FD = FunctionDecl::Create(Context,
1735 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001736 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001737 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001738 SC_Static,
1739 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001740 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001741
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001742 // Initialize debug info if necessary.
1743 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001744 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001745
John McCallf0c11f72011-03-31 08:03:29 +00001746 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001747 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001748
John McCallf0c11f72011-03-31 08:03:29 +00001749 // dst->x
1750 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1751 destField = CGF.Builder.CreateLoad(destField);
1752 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001753 destField = CGF.Builder.CreateStructGEP(destField, valueFieldIndex, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001754
John McCallf0c11f72011-03-31 08:03:29 +00001755 // src->x
1756 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1757 srcField = CGF.Builder.CreateLoad(srcField);
1758 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCallb62faef2013-01-22 03:56:22 +00001759 srcField = CGF.Builder.CreateStructGEP(srcField, valueFieldIndex, "x");
John McCallf0c11f72011-03-31 08:03:29 +00001760
1761 byrefInfo.emitCopy(CGF, destField, srcField);
1762 }
1763
1764 CGF.FinishFunction();
1765
1766 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001767}
1768
John McCallf0c11f72011-03-31 08:03:29 +00001769/// Build the copy helper for a __block variable.
1770static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001772 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001773 CodeGenModule::ByrefHelpers &info) {
1774 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001775 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf0c11f72011-03-31 08:03:29 +00001776}
1777
1778/// Generate code for a __block variable's dispose helper.
1779static llvm::Constant *
1780generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001781 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001782 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001783 CodeGenModule::ByrefHelpers &byrefInfo) {
1784 ASTContext &Context = CGF.getContext();
1785 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001786
John McCalld26bc762011-03-09 04:27:21 +00001787 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001788 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001789 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Mike Stump45031c02009-03-06 02:29:21 +00001791 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001792 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1793 FunctionType::ExtInfo(),
1794 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001795
John McCallf0c11f72011-03-31 08:03:29 +00001796 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001797 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001798
Mike Stump3899a7f2009-06-05 23:26:36 +00001799 // FIXME: We'd like to put these into a mergable by content, with
1800 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001801 llvm::Function *Fn =
1802 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001803 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001804 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001805
1806 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001807 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001808
John McCallf0c11f72011-03-31 08:03:29 +00001809 FunctionDecl *FD = FunctionDecl::Create(Context,
1810 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001811 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001812 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001813 SC_Static,
1814 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001815 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001816 // Initialize debug info if necessary.
1817 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001818 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001819
John McCallf0c11f72011-03-31 08:03:29 +00001820 if (byrefInfo.needsDispose()) {
1821 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1822 V = CGF.Builder.CreateLoad(V);
1823 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
John McCallb62faef2013-01-22 03:56:22 +00001824 V = CGF.Builder.CreateStructGEP(V, byrefValueIndex, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001825
John McCallf0c11f72011-03-31 08:03:29 +00001826 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001827 }
Mike Stump45031c02009-03-06 02:29:21 +00001828
John McCallf0c11f72011-03-31 08:03:29 +00001829 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001830
John McCallf0c11f72011-03-31 08:03:29 +00001831 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001832}
1833
John McCallf0c11f72011-03-31 08:03:29 +00001834/// Build the dispose helper for a __block variable.
1835static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001836 llvm::StructType &byrefType,
John McCallb62faef2013-01-22 03:56:22 +00001837 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001838 CodeGenModule::ByrefHelpers &info) {
1839 CodeGenFunction CGF(CGM);
John McCallb62faef2013-01-22 03:56:22 +00001840 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stump45031c02009-03-06 02:29:21 +00001841}
1842
John McCallb62faef2013-01-22 03:56:22 +00001843/// Lazily build the copy and dispose helpers for a __block variable
1844/// with the given information.
John McCallf0c11f72011-03-31 08:03:29 +00001845template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001846 llvm::StructType &byrefTy,
John McCallb62faef2013-01-22 03:56:22 +00001847 unsigned byrefValueIndex,
John McCallf0c11f72011-03-31 08:03:29 +00001848 T &byrefInfo) {
1849 // Increase the field's alignment to be at least pointer alignment,
1850 // since the layout of the byref struct will guarantee at least that.
1851 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1852 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1853
1854 llvm::FoldingSetNodeID id;
1855 byrefInfo.Profile(id);
1856
1857 void *insertPos;
1858 CodeGenModule::ByrefHelpers *node
1859 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1860 if (node) return static_cast<T*>(node);
1861
John McCallb62faef2013-01-22 03:56:22 +00001862 byrefInfo.CopyHelper =
1863 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1864 byrefInfo.DisposeHelper =
1865 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001866
1867 T *copy = new (CGM.getContext()) T(byrefInfo);
1868 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1869 return copy;
1870}
1871
John McCallb62faef2013-01-22 03:56:22 +00001872/// Build the copy and dispose helpers for the given __block variable
1873/// emission. Places the helpers in the global cache. Returns null
1874/// if no helpers are required.
John McCallf0c11f72011-03-31 08:03:29 +00001875CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001876CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001877 const AutoVarEmission &emission) {
1878 const VarDecl &var = *emission.Variable;
1879 QualType type = var.getType();
1880
John McCallb62faef2013-01-22 03:56:22 +00001881 unsigned byrefValueIndex = getByRefValueLLVMField(&var);
1882
John McCallf0c11f72011-03-31 08:03:29 +00001883 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1884 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1885 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1886
1887 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
John McCallb62faef2013-01-22 03:56:22 +00001888 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf0c11f72011-03-31 08:03:29 +00001889 }
1890
John McCallf85e1932011-06-15 23:02:42 +00001891 // Otherwise, if we don't have a retainable type, there's nothing to do.
1892 // that the runtime does extra copies.
1893 if (!type->isObjCRetainableType()) return 0;
1894
1895 Qualifiers qs = type.getQualifiers();
1896
1897 // If we have lifetime, that dominates.
1898 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001899 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001900
1901 switch (lifetime) {
1902 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1903
1904 // These are just bits as far as the runtime is concerned.
1905 case Qualifiers::OCL_ExplicitNone:
1906 case Qualifiers::OCL_Autoreleasing:
1907 return 0;
1908
1909 // Tell the runtime that this is ARC __weak, called by the
1910 // byref routines.
1911 case Qualifiers::OCL_Weak: {
1912 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001913 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001914 }
1915
1916 // ARC __strong __block variables need to be retained.
1917 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001918 // Block pointers need to be copied, and there's no direct
1919 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001920 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001921 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001922 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001923
1924 // Otherwise, we transfer ownership of the retain from the stack
1925 // to the heap.
1926 } else {
1927 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
John McCallb62faef2013-01-22 03:56:22 +00001928 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
John McCallf85e1932011-06-15 23:02:42 +00001929 }
1930 }
1931 llvm_unreachable("fell out of lifetime switch!");
1932 }
1933
John McCallf0c11f72011-03-31 08:03:29 +00001934 BlockFieldFlags flags;
1935 if (type->isBlockPointerType()) {
1936 flags |= BLOCK_FIELD_IS_BLOCK;
1937 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1938 type->isObjCObjectPointerType()) {
1939 flags |= BLOCK_FIELD_IS_OBJECT;
1940 } else {
1941 return 0;
1942 }
1943
1944 if (type.isObjCGCWeak())
1945 flags |= BLOCK_FIELD_IS_WEAK;
1946
1947 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
John McCallb62faef2013-01-22 03:56:22 +00001948 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001949}
1950
John McCall5af02db2011-03-31 01:59:53 +00001951unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1952 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1953
1954 return ByRefValueInfo.find(VD)->second.second;
1955}
1956
1957llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1958 const VarDecl *V) {
1959 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1960 Loc = Builder.CreateLoad(Loc);
1961 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1962 V->getNameAsString());
1963 return Loc;
1964}
1965
1966/// BuildByRefType - This routine changes a __block variable declared as T x
1967/// into:
1968///
1969/// struct {
1970/// void *__isa;
1971/// void *__forwarding;
1972/// int32_t __flags;
1973/// int32_t __size;
1974/// void *__copy_helper; // only if needed
1975/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001976/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00001977/// char padding[X]; // only if needed
1978/// T x;
1979/// } x
1980///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001981llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1982 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001983 if (Info.first)
1984 return Info.first;
1985
1986 QualType Ty = D->getType();
1987
Chris Lattner5f9e2722011-07-23 10:55:15 +00001988 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001989
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001990 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001991 llvm::StructType::create(getLLVMContext(),
1992 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001993
1994 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001995 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001996
1997 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001998 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001999
2000 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00002001 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00002002
2003 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00002004 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00002005 // Note that this must match *exactly* the logic in buildByrefHelpers.
2006 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00002007 if (HasCopyAndDispose) {
2008 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002009 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002010
2011 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00002012 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002013 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002014 bool HasByrefExtendedLayout = false;
2015 Qualifiers::ObjCLifetime Lifetime;
2016 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2017 HasByrefExtendedLayout)
2018 /// void *__byref_variable_layout;
2019 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002020
2021 bool Packed = false;
2022 CharUnits Align = getContext().getDeclAlign(D);
2023 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
2024 // We have to insert padding.
2025
2026 // The struct above has 2 32-bit integers.
2027 unsigned CurrentOffsetInBytes = 4 * 2;
2028
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002029 // And either 2, 3, 4 or 5 pointers.
2030 unsigned noPointers = 2;
2031 if (HasCopyAndDispose)
2032 noPointers += 2;
2033 if (HasByrefExtendedLayout)
2034 noPointers += 1;
2035
2036 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002037
2038 // Align the offset.
2039 unsigned AlignedOffsetInBytes =
2040 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2041
2042 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2043 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00002044 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00002045 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00002046 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00002047 if (NumPaddingBytes > 1)
2048 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2049
John McCall0774cb82011-05-15 01:53:33 +00002050 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00002051
2052 // We want a packed struct.
2053 Packed = true;
2054 }
2055 }
2056
2057 // T x;
John McCall0774cb82011-05-15 01:53:33 +00002058 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00002059
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002060 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00002061
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002062 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00002063
John McCall0774cb82011-05-15 01:53:33 +00002064 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00002065
2066 return Info.first;
2067}
2068
2069/// Initialize the structural components of a __block variable, i.e.
2070/// everything but the actual object.
2071void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002072 // Find the address of the local.
2073 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002074
John McCallf0c11f72011-03-31 08:03:29 +00002075 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002076 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002077 cast<llvm::PointerType>(addr->getType())->getElementType());
2078
2079 // Build the byref helpers if necessary. This is null if we don't need any.
2080 CodeGenModule::ByrefHelpers *helpers =
2081 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002082
2083 const VarDecl &D = *emission.Variable;
2084 QualType type = D.getType();
2085
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002086 bool HasByrefExtendedLayout;
2087 Qualifiers::ObjCLifetime ByrefLifetime;
2088 bool ByRefHasLifetime =
2089 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2090
John McCallf0c11f72011-03-31 08:03:29 +00002091 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002092
2093 // Initialize the 'isa', which is just 0 or 1.
2094 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002095 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002096 isa = 1;
2097 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2098 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2099
2100 // Store the address of the variable into its own forwarding pointer.
2101 Builder.CreateStore(addr,
2102 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2103
2104 // Blocks ABI:
2105 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002106 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002107 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002108 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2109 if (ByRefHasLifetime) {
2110 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2111 else switch (ByrefLifetime) {
2112 case Qualifiers::OCL_Strong:
2113 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2114 break;
2115 case Qualifiers::OCL_Weak:
2116 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2117 break;
2118 case Qualifiers::OCL_ExplicitNone:
2119 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2120 break;
2121 case Qualifiers::OCL_None:
2122 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2123 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2124 break;
2125 default:
2126 break;
2127 }
2128 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2129 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2130 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2131 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2132 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2133 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2134 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2135 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2136 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2137 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2138 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2139 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2140 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2141 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2142 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2143 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2144 }
2145 printf("\n");
2146 }
2147 }
2148
John McCall5af02db2011-03-31 01:59:53 +00002149 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2150 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2151
John McCallf0c11f72011-03-31 08:03:29 +00002152 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2153 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002154 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2155
John McCallf0c11f72011-03-31 08:03:29 +00002156 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002157 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002158 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002159
2160 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002161 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002162 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002163 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2164 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2165 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2166 "byref.layout");
2167 // cast destination to pointer to source type.
2168 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2169 DesTy = DesTy->getPointerTo();
2170 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2171 Builder.CreateStore(ByrefLayoutInfo, BC);
2172 }
John McCall5af02db2011-03-31 01:59:53 +00002173}
2174
John McCalld16c2cf2011-02-08 08:22:06 +00002175void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002176 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002177 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002178 V = Builder.CreateBitCast(V, Int8PtrTy);
2179 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002180 Builder.CreateCall2(F, V, N);
2181}
John McCall5af02db2011-03-31 01:59:53 +00002182
2183namespace {
2184 struct CallBlockRelease : EHScopeStack::Cleanup {
2185 llvm::Value *Addr;
2186 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2187
John McCallad346f42011-07-12 20:27:29 +00002188 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002189 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002190 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2191 }
2192 };
2193}
2194
2195/// Enter a cleanup to destroy a __block variable. Note that this
2196/// cleanup should be a no-op if the variable hasn't left the stack
2197/// yet; if a cleanup is required for the variable itself, that needs
2198/// to be done externally.
2199void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2200 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002201 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002202 return;
2203
2204 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2205}
John McCall13db5cf2011-09-09 20:41:01 +00002206
2207/// Adjust the declaration of something from the blocks API.
2208static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2209 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002210 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002211
2212 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2213 if (GV->isDeclaration() &&
2214 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2215 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2216}
2217
2218llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2219 if (BlockObjectDispose)
2220 return BlockObjectDispose;
2221
2222 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2223 llvm::FunctionType *fty
2224 = llvm::FunctionType::get(VoidTy, args, false);
2225 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2226 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2227 return BlockObjectDispose;
2228}
2229
2230llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2231 if (BlockObjectAssign)
2232 return BlockObjectAssign;
2233
2234 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2235 llvm::FunctionType *fty
2236 = llvm::FunctionType::get(VoidTy, args, false);
2237 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2238 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2239 return BlockObjectAssign;
2240}
2241
2242llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2243 if (NSConcreteGlobalBlock)
2244 return NSConcreteGlobalBlock;
2245
2246 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2247 Int8PtrTy->getPointerTo(), 0);
2248 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2249 return NSConcreteGlobalBlock;
2250}
2251
2252llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2253 if (NSConcreteStackBlock)
2254 return NSConcreteStackBlock;
2255
2256 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2257 Int8PtrTy->getPointerTo(), 0);
2258 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2259 return NSConcreteStackBlock;
2260}