blob: b199e763252cc483d4c5ba436ad91db333c3e717 [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
Mike Stumpa99038c2009-02-28 09:07:16 +00001249
John McCall6b5a61b2011-02-07 10:33:21 +00001250llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001251CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001252 ASTContext &C = getContext();
1253
1254 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001255 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1256 args.push_back(&dstDecl);
1257 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1258 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Mike Stumpa4f668f2009-03-06 01:33:24 +00001260 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001261 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1262 FunctionType::ExtInfo(),
1263 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001264
John McCall6b5a61b2011-02-07 10:33:21 +00001265 // FIXME: it would be nice if these were mergeable with things with
1266 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001267 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001268
1269 llvm::Function *Fn =
1270 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001271 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001272
1273 IdentifierInfo *II
1274 = &CGM.getContext().Idents.get("__copy_helper_block_");
1275
Devang Patel58dc5ca2011-05-02 20:37:08 +00001276 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001277 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001278
John McCall6b5a61b2011-02-07 10:33:21 +00001279 FunctionDecl *FD = FunctionDecl::Create(C,
1280 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001281 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001282 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001283 SC_Static,
1284 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001285 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001286 false);
John McCalld26bc762011-03-09 04:27:21 +00001287 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001288
Chris Lattner2acc6e32011-07-18 04:24:23 +00001289 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001290
John McCalld26bc762011-03-09 04:27:21 +00001291 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001292 src = Builder.CreateLoad(src);
1293 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001294
John McCalld26bc762011-03-09 04:27:21 +00001295 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001296 dst = Builder.CreateLoad(dst);
1297 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001298
John McCall6b5a61b2011-02-07 10:33:21 +00001299 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001300
John McCall6b5a61b2011-02-07 10:33:21 +00001301 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1302 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1303 const VarDecl *variable = ci->getVariable();
1304 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001305
John McCall6b5a61b2011-02-07 10:33:21 +00001306 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1307 if (capture.isConstant()) continue;
1308
1309 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001310 BlockFieldFlags flags;
1311
John McCall015f33b2012-10-17 02:28:37 +00001312 bool useARCWeakCopy = false;
1313 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001314
1315 if (copyExpr) {
1316 assert(!ci->isByRef());
1317 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001318
John McCall6b5a61b2011-02-07 10:33:21 +00001319 } else if (ci->isByRef()) {
1320 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001321 if (type.isObjCGCWeak())
1322 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001323
John McCallf85e1932011-06-15 23:02:42 +00001324 } else if (type->isObjCRetainableType()) {
1325 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001326 bool isBlockPointer = type->isBlockPointerType();
1327 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001328 flags = BLOCK_FIELD_IS_BLOCK;
1329
1330 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001331 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001332 Qualifiers qs = type.getQualifiers();
1333
John McCall015f33b2012-10-17 02:28:37 +00001334 // We need to register __weak direct captures with the runtime.
1335 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1336 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001337
John McCall015f33b2012-10-17 02:28:37 +00001338 // We need to retain the copied value for __strong direct captures.
1339 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1340 // If it's a block pointer, we have to copy the block and
1341 // assign that to the destination pointer, so we might as
1342 // well use _Block_object_assign. Otherwise we can avoid that.
1343 if (!isBlockPointer)
1344 useARCStrongCopy = true;
1345
1346 // Otherwise the memcpy is fine.
1347 } else {
1348 continue;
1349 }
1350
1351 // Non-ARC captures of retainable pointers are strong and
1352 // therefore require a call to _Block_object_assign.
1353 } else {
1354 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001355 }
1356 } else {
1357 continue;
1358 }
John McCall6b5a61b2011-02-07 10:33:21 +00001359
1360 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001361 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1362 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001363
1364 // If there's an explicit copy expression, we do that.
1365 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001366 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001367 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001368 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001369 } else {
1370 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001371 if (useARCStrongCopy) {
1372 // At -O0, store null into the destination field (so that the
1373 // storeStrong doesn't over-release) and then call storeStrong.
1374 // This is a workaround to not having an initStrong call.
1375 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1376 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1377 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1378 Builder.CreateStore(null, dstField);
1379 EmitARCStoreStrongCall(dstField, srcValue, true);
1380
1381 // With optimization enabled, take advantage of the fact that
1382 // the blocks runtime guarantees a memcpy of the block data, and
1383 // just emit a retain of the src field.
1384 } else {
1385 EmitARCRetainNonBlock(srcValue);
1386
1387 // We don't need this anymore, so kill it. It's not quite
1388 // worth the annoyance to avoid creating it in the first place.
1389 cast<llvm::Instruction>(dstField)->eraseFromParent();
1390 }
1391 } else {
1392 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1393 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1394 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1395 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1396 }
Mike Stump08920992009-03-07 02:35:30 +00001397 }
1398 }
1399
John McCalld16c2cf2011-02-08 08:22:06 +00001400 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001401
John McCall5936e332011-02-15 09:22:45 +00001402 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001403}
1404
John McCall6b5a61b2011-02-07 10:33:21 +00001405llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001406CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001407 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001408
John McCall6b5a61b2011-02-07 10:33:21 +00001409 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001410 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1411 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Mike Stumpa4f668f2009-03-06 01:33:24 +00001413 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001414 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1415 FunctionType::ExtInfo(),
1416 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001417
Mike Stump3899a7f2009-06-05 23:26:36 +00001418 // FIXME: We'd like to put these into a mergable by content, with
1419 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001420 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001421
1422 llvm::Function *Fn =
1423 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001424 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001425
Devang Patel58dc5ca2011-05-02 20:37:08 +00001426 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001427 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001428
Mike Stumpa4f668f2009-03-06 01:33:24 +00001429 IdentifierInfo *II
1430 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1431
John McCall6b5a61b2011-02-07 10:33:21 +00001432 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001433 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001434 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001435 SC_Static,
1436 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001437 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001438 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001439
Chris Lattner2acc6e32011-07-18 04:24:23 +00001440 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001441
John McCalld26bc762011-03-09 04:27:21 +00001442 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001443 src = Builder.CreateLoad(src);
1444 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001445
John McCall6b5a61b2011-02-07 10:33:21 +00001446 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1447
John McCalld16c2cf2011-02-08 08:22:06 +00001448 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001449
1450 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1451 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1452 const VarDecl *variable = ci->getVariable();
1453 QualType type = variable->getType();
1454
1455 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1456 if (capture.isConstant()) continue;
1457
John McCalld16c2cf2011-02-08 08:22:06 +00001458 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001459 const CXXDestructorDecl *dtor = 0;
1460
John McCall015f33b2012-10-17 02:28:37 +00001461 bool useARCWeakDestroy = false;
1462 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001463
John McCall6b5a61b2011-02-07 10:33:21 +00001464 if (ci->isByRef()) {
1465 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001466 if (type.isObjCGCWeak())
1467 flags |= BLOCK_FIELD_IS_WEAK;
1468 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1469 if (record->hasTrivialDestructor())
1470 continue;
1471 dtor = record->getDestructor();
1472 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001473 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001474 if (type->isBlockPointerType())
1475 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001476
John McCallf85e1932011-06-15 23:02:42 +00001477 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001478 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001479 Qualifiers qs = type.getQualifiers();
1480
1481 // Don't generate special dispose logic for a captured object
1482 // unless it's __strong or __weak.
1483 if (!qs.hasStrongOrWeakObjCLifetime())
1484 continue;
1485
1486 // Support __weak direct captures.
1487 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001488 useARCWeakDestroy = true;
1489
1490 // Tools really want us to use objc_storeStrong here.
1491 else
1492 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001493 }
1494 } else {
1495 continue;
1496 }
John McCall6b5a61b2011-02-07 10:33:21 +00001497
1498 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001499 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001500
1501 // If there's an explicit copy expression, we do that.
1502 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001503 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001504
John McCallf85e1932011-06-15 23:02:42 +00001505 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001506 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001507 EmitARCDestroyWeak(srcField);
1508
John McCall015f33b2012-10-17 02:28:37 +00001509 // Destroy strong objects with a call if requested.
1510 } else if (useARCStrongDestroy) {
1511 EmitARCDestroyStrong(srcField, /*precise*/ false);
1512
John McCall6b5a61b2011-02-07 10:33:21 +00001513 // Otherwise we call _Block_object_dispose. It wouldn't be too
1514 // hard to just emit this as a cleanup if we wanted to make sure
1515 // that things were done in reverse.
1516 } else {
1517 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001518 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001519 BuildBlockRelease(value, flags);
1520 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001521 }
1522
John McCall6b5a61b2011-02-07 10:33:21 +00001523 cleanups.ForceCleanup();
1524
John McCalld16c2cf2011-02-08 08:22:06 +00001525 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001526
John McCall5936e332011-02-15 09:22:45 +00001527 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001528}
1529
John McCallf0c11f72011-03-31 08:03:29 +00001530namespace {
1531
1532/// Emits the copy/dispose helper functions for a __block object of id type.
1533class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1534 BlockFieldFlags Flags;
1535
1536public:
1537 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1538 : ByrefHelpers(alignment), Flags(flags) {}
1539
John McCall36170192011-03-31 09:19:20 +00001540 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1541 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001542 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1543
1544 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1545 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1546
1547 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1548
1549 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1550 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1551 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1552 }
1553
1554 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1555 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1556 llvm::Value *value = CGF.Builder.CreateLoad(field);
1557
1558 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1559 }
1560
1561 void profileImpl(llvm::FoldingSetNodeID &id) const {
1562 id.AddInteger(Flags.getBitMask());
1563 }
1564};
1565
John McCallf85e1932011-06-15 23:02:42 +00001566/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1567class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1568public:
1569 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1570
1571 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1572 llvm::Value *srcField) {
1573 CGF.EmitARCMoveWeak(destField, srcField);
1574 }
1575
1576 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1577 CGF.EmitARCDestroyWeak(field);
1578 }
1579
1580 void profileImpl(llvm::FoldingSetNodeID &id) const {
1581 // 0 is distinguishable from all pointers and byref flags
1582 id.AddInteger(0);
1583 }
1584};
1585
1586/// Emits the copy/dispose helpers for an ARC __block __strong variable
1587/// that's not of block-pointer type.
1588class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1589public:
1590 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1591
1592 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1593 llvm::Value *srcField) {
1594 // Do a "move" by copying the value and then zeroing out the old
1595 // variable.
1596
John McCalla59e4b72011-11-09 03:17:26 +00001597 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1598 value->setAlignment(Alignment.getQuantity());
1599
John McCallf85e1932011-06-15 23:02:42 +00001600 llvm::Value *null =
1601 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001602
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001603 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahanianba3c9ca2013-01-05 00:32:13 +00001604 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1605 store->setAlignment(Alignment.getQuantity());
Fariborz Jahanian7a77f192013-01-04 23:32:24 +00001606 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1607 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1608 return;
1609 }
John McCalla59e4b72011-11-09 03:17:26 +00001610 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1611 store->setAlignment(Alignment.getQuantity());
1612
1613 store = CGF.Builder.CreateStore(null, srcField);
1614 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001615 }
1616
1617 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001618 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001619 }
1620
1621 void profileImpl(llvm::FoldingSetNodeID &id) const {
1622 // 1 is distinguishable from all pointers and byref flags
1623 id.AddInteger(1);
1624 }
1625};
1626
John McCalla59e4b72011-11-09 03:17:26 +00001627/// Emits the copy/dispose helpers for an ARC __block __strong
1628/// variable that's of block-pointer type.
1629class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1630public:
1631 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1632
1633 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1634 llvm::Value *srcField) {
1635 // Do the copy with objc_retainBlock; that's all that
1636 // _Block_object_assign would do anyway, and we'd have to pass the
1637 // right arguments to make sure it doesn't get no-op'ed.
1638 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1639 oldValue->setAlignment(Alignment.getQuantity());
1640
1641 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1642
1643 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1644 store->setAlignment(Alignment.getQuantity());
1645 }
1646
1647 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001648 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001649 }
1650
1651 void profileImpl(llvm::FoldingSetNodeID &id) const {
1652 // 2 is distinguishable from all pointers and byref flags
1653 id.AddInteger(2);
1654 }
1655};
1656
John McCallf0c11f72011-03-31 08:03:29 +00001657/// Emits the copy/dispose helpers for a __block variable with a
1658/// nontrivial copy constructor or destructor.
1659class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1660 QualType VarType;
1661 const Expr *CopyExpr;
1662
1663public:
1664 CXXByrefHelpers(CharUnits alignment, QualType type,
1665 const Expr *copyExpr)
1666 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1667
1668 bool needsCopy() const { return CopyExpr != 0; }
1669 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1670 llvm::Value *srcField) {
1671 if (!CopyExpr) return;
1672 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1673 }
1674
1675 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1676 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1677 CGF.PushDestructorCleanup(VarType, field);
1678 CGF.PopCleanupBlocks(cleanupDepth);
1679 }
1680
1681 void profileImpl(llvm::FoldingSetNodeID &id) const {
1682 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1683 }
1684};
1685} // end anonymous namespace
1686
1687static llvm::Constant *
1688generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001689 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001690 CodeGenModule::ByrefHelpers &byrefInfo) {
1691 ASTContext &Context = CGF.getContext();
1692
1693 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001694
John McCalld26bc762011-03-09 04:27:21 +00001695 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001696 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001697 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001698
John McCallf0c11f72011-03-31 08:03:29 +00001699 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001700 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Mike Stump45031c02009-03-06 02:29:21 +00001702 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001703 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1704 FunctionType::ExtInfo(),
1705 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001706
John McCallf0c11f72011-03-31 08:03:29 +00001707 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001708 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001709
Mike Stump3899a7f2009-06-05 23:26:36 +00001710 // FIXME: We'd like to put these into a mergable by content, with
1711 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001712 llvm::Function *Fn =
1713 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001714 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001715
1716 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001717 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001718
John McCallf0c11f72011-03-31 08:03:29 +00001719 FunctionDecl *FD = FunctionDecl::Create(Context,
1720 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001721 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001722 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001723 SC_Static,
1724 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001725 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001726
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001727 // Initialize debug info if necessary.
1728 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001729 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001730
John McCallf0c11f72011-03-31 08:03:29 +00001731 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001732 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001733
John McCallf0c11f72011-03-31 08:03:29 +00001734 // dst->x
1735 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1736 destField = CGF.Builder.CreateLoad(destField);
1737 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1738 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001739
John McCallf0c11f72011-03-31 08:03:29 +00001740 // src->x
1741 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1742 srcField = CGF.Builder.CreateLoad(srcField);
1743 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1744 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1745
1746 byrefInfo.emitCopy(CGF, destField, srcField);
1747 }
1748
1749 CGF.FinishFunction();
1750
1751 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001752}
1753
John McCallf0c11f72011-03-31 08:03:29 +00001754/// Build the copy helper for a __block variable.
1755static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001756 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001757 CodeGenModule::ByrefHelpers &info) {
1758 CodeGenFunction CGF(CGM);
1759 return generateByrefCopyHelper(CGF, byrefType, info);
1760}
1761
1762/// Generate code for a __block variable's dispose helper.
1763static llvm::Constant *
1764generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001765 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001766 CodeGenModule::ByrefHelpers &byrefInfo) {
1767 ASTContext &Context = CGF.getContext();
1768 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001769
John McCalld26bc762011-03-09 04:27:21 +00001770 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001771 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001772 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Mike Stump45031c02009-03-06 02:29:21 +00001774 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001775 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1776 FunctionType::ExtInfo(),
1777 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001778
John McCallf0c11f72011-03-31 08:03:29 +00001779 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001780 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001781
Mike Stump3899a7f2009-06-05 23:26:36 +00001782 // FIXME: We'd like to put these into a mergable by content, with
1783 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001784 llvm::Function *Fn =
1785 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001786 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001787 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001788
1789 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001790 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001791
John McCallf0c11f72011-03-31 08:03:29 +00001792 FunctionDecl *FD = FunctionDecl::Create(Context,
1793 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001794 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001795 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001796 SC_Static,
1797 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001798 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001799 // Initialize debug info if necessary.
1800 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001801 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001802
John McCallf0c11f72011-03-31 08:03:29 +00001803 if (byrefInfo.needsDispose()) {
1804 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1805 V = CGF.Builder.CreateLoad(V);
1806 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1807 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001808
John McCallf0c11f72011-03-31 08:03:29 +00001809 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001810 }
Mike Stump45031c02009-03-06 02:29:21 +00001811
John McCallf0c11f72011-03-31 08:03:29 +00001812 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001813
John McCallf0c11f72011-03-31 08:03:29 +00001814 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001815}
1816
John McCallf0c11f72011-03-31 08:03:29 +00001817/// Build the dispose helper for a __block variable.
1818static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001819 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001820 CodeGenModule::ByrefHelpers &info) {
1821 CodeGenFunction CGF(CGM);
1822 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001823}
1824
John McCallf0c11f72011-03-31 08:03:29 +00001825///
1826template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001827 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001828 T &byrefInfo) {
1829 // Increase the field's alignment to be at least pointer alignment,
1830 // since the layout of the byref struct will guarantee at least that.
1831 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1832 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1833
1834 llvm::FoldingSetNodeID id;
1835 byrefInfo.Profile(id);
1836
1837 void *insertPos;
1838 CodeGenModule::ByrefHelpers *node
1839 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1840 if (node) return static_cast<T*>(node);
1841
1842 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1843 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1844
1845 T *copy = new (CGM.getContext()) T(byrefInfo);
1846 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1847 return copy;
1848}
1849
1850CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001851CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001852 const AutoVarEmission &emission) {
1853 const VarDecl &var = *emission.Variable;
1854 QualType type = var.getType();
1855
1856 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1857 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1858 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1859
1860 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1861 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1862 }
1863
John McCallf85e1932011-06-15 23:02:42 +00001864 // Otherwise, if we don't have a retainable type, there's nothing to do.
1865 // that the runtime does extra copies.
1866 if (!type->isObjCRetainableType()) return 0;
1867
1868 Qualifiers qs = type.getQualifiers();
1869
1870 // If we have lifetime, that dominates.
1871 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001872 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001873
1874 switch (lifetime) {
1875 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1876
1877 // These are just bits as far as the runtime is concerned.
1878 case Qualifiers::OCL_ExplicitNone:
1879 case Qualifiers::OCL_Autoreleasing:
1880 return 0;
1881
1882 // Tell the runtime that this is ARC __weak, called by the
1883 // byref routines.
1884 case Qualifiers::OCL_Weak: {
1885 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1886 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1887 }
1888
1889 // ARC __strong __block variables need to be retained.
1890 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001891 // Block pointers need to be copied, and there's no direct
1892 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001893 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001894 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001895 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1896
1897 // Otherwise, we transfer ownership of the retain from the stack
1898 // to the heap.
1899 } else {
1900 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1901 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1902 }
1903 }
1904 llvm_unreachable("fell out of lifetime switch!");
1905 }
1906
John McCallf0c11f72011-03-31 08:03:29 +00001907 BlockFieldFlags flags;
1908 if (type->isBlockPointerType()) {
1909 flags |= BLOCK_FIELD_IS_BLOCK;
1910 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1911 type->isObjCObjectPointerType()) {
1912 flags |= BLOCK_FIELD_IS_OBJECT;
1913 } else {
1914 return 0;
1915 }
1916
1917 if (type.isObjCGCWeak())
1918 flags |= BLOCK_FIELD_IS_WEAK;
1919
1920 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1921 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001922}
1923
John McCall5af02db2011-03-31 01:59:53 +00001924unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1925 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1926
1927 return ByRefValueInfo.find(VD)->second.second;
1928}
1929
1930llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1931 const VarDecl *V) {
1932 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1933 Loc = Builder.CreateLoad(Loc);
1934 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1935 V->getNameAsString());
1936 return Loc;
1937}
1938
1939/// BuildByRefType - This routine changes a __block variable declared as T x
1940/// into:
1941///
1942/// struct {
1943/// void *__isa;
1944/// void *__forwarding;
1945/// int32_t __flags;
1946/// int32_t __size;
1947/// void *__copy_helper; // only if needed
1948/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001949/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00001950/// char padding[X]; // only if needed
1951/// T x;
1952/// } x
1953///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001954llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1955 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001956 if (Info.first)
1957 return Info.first;
1958
1959 QualType Ty = D->getType();
1960
Chris Lattner5f9e2722011-07-23 10:55:15 +00001961 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001962
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001963 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001964 llvm::StructType::create(getLLVMContext(),
1965 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001966
1967 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001968 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001969
1970 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001971 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001972
1973 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001974 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001975
1976 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001977 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00001978 // Note that this must match *exactly* the logic in buildByrefHelpers.
1979 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00001980 if (HasCopyAndDispose) {
1981 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001982 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001983
1984 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001985 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001986 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001987 bool HasByrefExtendedLayout = false;
1988 Qualifiers::ObjCLifetime Lifetime;
1989 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
1990 HasByrefExtendedLayout)
1991 /// void *__byref_variable_layout;
1992 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001993
1994 bool Packed = false;
1995 CharUnits Align = getContext().getDeclAlign(D);
1996 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1997 // We have to insert padding.
1998
1999 // The struct above has 2 32-bit integers.
2000 unsigned CurrentOffsetInBytes = 4 * 2;
2001
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002002 // And either 2, 3, 4 or 5 pointers.
2003 unsigned noPointers = 2;
2004 if (HasCopyAndDispose)
2005 noPointers += 2;
2006 if (HasByrefExtendedLayout)
2007 noPointers += 1;
2008
2009 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00002010
2011 // Align the offset.
2012 unsigned AlignedOffsetInBytes =
2013 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2014
2015 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2016 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00002017 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00002018 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00002019 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00002020 if (NumPaddingBytes > 1)
2021 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2022
John McCall0774cb82011-05-15 01:53:33 +00002023 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00002024
2025 // We want a packed struct.
2026 Packed = true;
2027 }
2028 }
2029
2030 // T x;
John McCall0774cb82011-05-15 01:53:33 +00002031 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00002032
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002033 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00002034
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002035 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00002036
John McCall0774cb82011-05-15 01:53:33 +00002037 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00002038
2039 return Info.first;
2040}
2041
2042/// Initialize the structural components of a __block variable, i.e.
2043/// everything but the actual object.
2044void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002045 // Find the address of the local.
2046 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002047
John McCallf0c11f72011-03-31 08:03:29 +00002048 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002049 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002050 cast<llvm::PointerType>(addr->getType())->getElementType());
2051
2052 // Build the byref helpers if necessary. This is null if we don't need any.
2053 CodeGenModule::ByrefHelpers *helpers =
2054 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002055
2056 const VarDecl &D = *emission.Variable;
2057 QualType type = D.getType();
2058
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002059 bool HasByrefExtendedLayout;
2060 Qualifiers::ObjCLifetime ByrefLifetime;
2061 bool ByRefHasLifetime =
2062 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2063
John McCallf0c11f72011-03-31 08:03:29 +00002064 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002065
2066 // Initialize the 'isa', which is just 0 or 1.
2067 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002068 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002069 isa = 1;
2070 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2071 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2072
2073 // Store the address of the variable into its own forwarding pointer.
2074 Builder.CreateStore(addr,
2075 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2076
2077 // Blocks ABI:
2078 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002079 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002080 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002081 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2082 if (ByRefHasLifetime) {
2083 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2084 else switch (ByrefLifetime) {
2085 case Qualifiers::OCL_Strong:
2086 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2087 break;
2088 case Qualifiers::OCL_Weak:
2089 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2090 break;
2091 case Qualifiers::OCL_ExplicitNone:
2092 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2093 break;
2094 case Qualifiers::OCL_None:
2095 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2096 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2097 break;
2098 default:
2099 break;
2100 }
2101 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2102 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2103 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2104 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2105 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2106 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2107 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2108 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2109 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2110 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2111 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2112 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2113 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2114 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2115 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2116 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2117 }
2118 printf("\n");
2119 }
2120 }
2121
John McCall5af02db2011-03-31 01:59:53 +00002122 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2123 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2124
John McCallf0c11f72011-03-31 08:03:29 +00002125 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2126 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002127 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2128
John McCallf0c11f72011-03-31 08:03:29 +00002129 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002130 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002131 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002132
2133 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002134 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002135 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002136 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2137 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2138 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2139 "byref.layout");
2140 // cast destination to pointer to source type.
2141 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2142 DesTy = DesTy->getPointerTo();
2143 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2144 Builder.CreateStore(ByrefLayoutInfo, BC);
2145 }
John McCall5af02db2011-03-31 01:59:53 +00002146}
2147
John McCalld16c2cf2011-02-08 08:22:06 +00002148void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002149 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002150 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002151 V = Builder.CreateBitCast(V, Int8PtrTy);
2152 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002153 Builder.CreateCall2(F, V, N);
2154}
John McCall5af02db2011-03-31 01:59:53 +00002155
2156namespace {
2157 struct CallBlockRelease : EHScopeStack::Cleanup {
2158 llvm::Value *Addr;
2159 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2160
John McCallad346f42011-07-12 20:27:29 +00002161 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002162 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002163 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2164 }
2165 };
2166}
2167
2168/// Enter a cleanup to destroy a __block variable. Note that this
2169/// cleanup should be a no-op if the variable hasn't left the stack
2170/// yet; if a cleanup is required for the variable itself, that needs
2171/// to be done externally.
2172void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2173 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002174 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002175 return;
2176
2177 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2178}
John McCall13db5cf2011-09-09 20:41:01 +00002179
2180/// Adjust the declaration of something from the blocks API.
2181static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2182 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002183 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002184
2185 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2186 if (GV->isDeclaration() &&
2187 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2188 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2189}
2190
2191llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2192 if (BlockObjectDispose)
2193 return BlockObjectDispose;
2194
2195 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2196 llvm::FunctionType *fty
2197 = llvm::FunctionType::get(VoidTy, args, false);
2198 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2199 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2200 return BlockObjectDispose;
2201}
2202
2203llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2204 if (BlockObjectAssign)
2205 return BlockObjectAssign;
2206
2207 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2208 llvm::FunctionType *fty
2209 = llvm::FunctionType::get(VoidTy, args, false);
2210 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2211 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2212 return BlockObjectAssign;
2213}
2214
2215llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2216 if (NSConcreteGlobalBlock)
2217 return NSConcreteGlobalBlock;
2218
2219 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2220 Int8PtrTy->getPointerTo(), 0);
2221 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2222 return NSConcreteGlobalBlock;
2223}
2224
2225llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2226 if (NSConcreteStackBlock)
2227 return NSConcreteStackBlock;
2228
2229 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2230 Int8PtrTy->getPointerTo(), 0);
2231 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2232 return NSConcreteStackBlock;
2233}