blob: 54bcb88ce3816fd7e266495bda143ab1d606105d [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;
185 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000186 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000187
John McCall6b5a61b2011-02-07 10:33:21 +0000188 BlockLayoutChunk(CharUnits align, CharUnits size,
189 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000190 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000191 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000192
John McCall6b5a61b2011-02-07 10:33:21 +0000193 /// Tell the block info that this chunk has the given field index.
194 void setIndex(CGBlockInfo &info, unsigned index) {
195 if (!Capture)
196 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000197 else
John McCall6b5a61b2011-02-07 10:33:21 +0000198 info.Captures[Capture->getVariable()]
199 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000200 }
John McCall6b5a61b2011-02-07 10:33:21 +0000201 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000202
John McCall6b5a61b2011-02-07 10:33:21 +0000203 /// Order by descending alignment.
204 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
205 return left.Alignment > right.Alignment;
206 }
207}
208
John McCall461c9c12011-02-08 03:07:00 +0000209/// Determines if the given type is safe for constant capture in C++.
210static bool isSafeForCXXConstantCapture(QualType type) {
211 const RecordType *recordType =
212 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
213
214 // Only records can be unsafe.
215 if (!recordType) return true;
216
217 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
218
219 // Maintain semantics for classes with non-trivial dtors or copy ctors.
220 if (!record->hasTrivialDestructor()) return false;
Richard Smith426391c2012-11-16 00:53:38 +0000221 if (record->hasNonTrivialCopyConstructor()) return false;
John McCall461c9c12011-02-08 03:07:00 +0000222
223 // Otherwise, we just have to make sure there aren't any mutable
224 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000225 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000226}
227
John McCall6b5a61b2011-02-07 10:33:21 +0000228/// It is illegal to modify a const object after initialization.
229/// Therefore, if a const object has a constant initializer, we don't
230/// actually need to keep storage for it in the block; we'll just
231/// rematerialize it at the start of the block function. This is
232/// acceptable because we make no promises about address stability of
233/// captured variables.
234static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000235 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000236 const VarDecl *var) {
237 QualType type = var->getType();
238
239 // We can only do this if the variable is const.
240 if (!type.isConstQualified()) return 0;
241
John McCall461c9c12011-02-08 03:07:00 +0000242 // Furthermore, in C++ we have to worry about mutable fields:
243 // C++ [dcl.type.cv]p4:
244 // Except that any class member declared mutable can be
245 // modified, any attempt to modify a const object during its
246 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000247 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000248 return 0;
249
250 // If the variable doesn't have any initializer (shouldn't this be
251 // invalid?), it's not clear what we should do. Maybe capture as
252 // zero?
253 const Expr *init = var->getInit();
254 if (!init) return 0;
255
Richard Smith2d6a5672012-01-14 04:30:29 +0000256 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000257}
258
259/// Get the low bit of a nonzero character count. This is the
260/// alignment of the nth byte if the 0th byte is universally aligned.
261static CharUnits getLowBit(CharUnits v) {
262 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
263}
264
265static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000266 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000267 ASTContext &C = CGM.getContext();
268
269 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
270 CharUnits ptrSize, ptrAlign, intSize, intAlign;
271 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
272 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
273
274 // Are there crazy embedded platforms where this isn't true?
275 assert(intSize <= ptrSize && "layout assumptions horribly violated");
276
277 CharUnits headerSize = ptrSize;
278 if (2 * intSize < ptrAlign) headerSize += ptrSize;
279 else headerSize += 2 * intSize;
280 headerSize += 2 * ptrSize;
281
282 info.BlockAlign = ptrAlign;
283 info.BlockSize = headerSize;
284
285 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000286 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
287 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000288 elementTypes.push_back(i8p);
289 elementTypes.push_back(intTy);
290 elementTypes.push_back(intTy);
291 elementTypes.push_back(i8p);
292 elementTypes.push_back(CGM.getBlockDescriptorType());
293
294 assert(elementTypes.size() == BlockHeaderSize);
295}
296
297/// Compute the layout of the given block. Attempts to lay the block
298/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000299static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
300 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000301 ASTContext &C = CGM.getContext();
302 const BlockDecl *block = info.getBlockDecl();
303
Chris Lattner5f9e2722011-07-23 10:55:15 +0000304 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000305 initializeForBlockHeader(CGM, info, elementTypes);
306
307 if (!block->hasCaptures()) {
308 info.StructureType =
309 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
310 info.CanBeGlobal = true;
311 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000312 }
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000313 else if (C.getLangOpts().ObjC1 &&
314 CGM.getLangOpts().getGC() == LangOptions::NonGC)
315 info.HasCapturedVariableLayout = true;
316
John McCall6b5a61b2011-02-07 10:33:21 +0000317 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000319 layout.reserve(block->capturesCXXThis() +
320 (block->capture_end() - block->capture_begin()));
321
322 CharUnits maxFieldAlign;
323
324 // First, 'this'.
325 if (block->capturesCXXThis()) {
326 const DeclContext *DC = block->getDeclContext();
327 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
328 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000329 QualType thisType;
330 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
331 thisType = C.getPointerType(C.getRecordType(RD));
332 else
333 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000334
Jay Foadef6de3d2011-07-11 09:56:20 +0000335 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000336 std::pair<CharUnits,CharUnits> tinfo
337 = CGM.getContext().getTypeInfoInChars(thisType);
338 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
339
340 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
341 }
342
343 // Next, all the block captures.
344 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
345 ce = block->capture_end(); ci != ce; ++ci) {
346 const VarDecl *variable = ci->getVariable();
347
348 if (ci->isByRef()) {
349 // We have to copy/dispose of the __block reference.
350 info.NeedsCopyDispose = true;
351
John McCall6b5a61b2011-02-07 10:33:21 +0000352 // Just use void* instead of a pointer to the byref type.
353 QualType byRefPtrTy = C.VoidPtrTy;
354
Jay Foadef6de3d2011-07-11 09:56:20 +0000355 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000356 std::pair<CharUnits,CharUnits> tinfo
357 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
358 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
359
360 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
361 &*ci, llvmType));
362 continue;
363 }
364
365 // Otherwise, build a layout chunk with the size and alignment of
366 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000367 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000368 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
369 continue;
370 }
371
John McCallf85e1932011-06-15 23:02:42 +0000372 // If we have a lifetime qualifier, honor it for capture purposes.
373 // That includes *not* copying it if it's __unsafe_unretained.
374 if (Qualifiers::ObjCLifetime lifetime
375 = variable->getType().getObjCLifetime()) {
376 switch (lifetime) {
377 case Qualifiers::OCL_None: llvm_unreachable("impossible");
378 case Qualifiers::OCL_ExplicitNone:
379 case Qualifiers::OCL_Autoreleasing:
380 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000381
John McCallf85e1932011-06-15 23:02:42 +0000382 case Qualifiers::OCL_Strong:
383 case Qualifiers::OCL_Weak:
384 info.NeedsCopyDispose = true;
385 }
386
387 // Block pointers require copy/dispose. So do Objective-C pointers.
388 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000389 info.NeedsCopyDispose = true;
390
391 // So do types that require non-trivial copy construction.
392 } else if (ci->hasCopyExpr()) {
393 info.NeedsCopyDispose = true;
394 info.HasCXXObject = true;
395
396 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000397 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000398 if (const CXXRecordDecl *record =
399 variable->getType()->getAsCXXRecordDecl()) {
400 if (!record->hasTrivialDestructor()) {
401 info.HasCXXObject = true;
402 info.NeedsCopyDispose = true;
403 }
404 }
405 }
406
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000407 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000408 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000409 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000410
John McCall6b5a61b2011-02-07 10:33:21 +0000411 maxFieldAlign = std::max(maxFieldAlign, align);
412
Jay Foadef6de3d2011-07-11 09:56:20 +0000413 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000414 CGM.getTypes().ConvertTypeForMem(VT);
415
John McCall6b5a61b2011-02-07 10:33:21 +0000416 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
417 }
418
419 // If that was everything, we're done here.
420 if (layout.empty()) {
421 info.StructureType =
422 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
423 info.CanBeGlobal = true;
424 return;
425 }
426
427 // Sort the layout by alignment. We have to use a stable sort here
428 // to get reproducible results. There should probably be an
429 // llvm::array_pod_stable_sort.
430 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000431
432 // Needed for blocks layout info.
433 info.BlockHeaderForcedGapOffset = info.BlockSize;
434 info.BlockHeaderForcedGapSize = CharUnits::Zero();
435
John McCall6b5a61b2011-02-07 10:33:21 +0000436 CharUnits &blockSize = info.BlockSize;
437 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
438
439 // Assuming that the first byte in the header is maximally aligned,
440 // get the alignment of the first byte following the header.
441 CharUnits endAlign = getLowBit(blockSize);
442
443 // If the end of the header isn't satisfactorily aligned for the
444 // maximum thing, look for things that are okay with the header-end
445 // alignment, and keep appending them until we get something that's
446 // aligned right. This algorithm is only guaranteed optimal if
447 // that condition is satisfied at some point; otherwise we can get
448 // things like:
449 // header // next byte has alignment 4
450 // something_with_size_5; // next byte has alignment 1
451 // something_with_alignment_8;
452 // which has 7 bytes of padding, as opposed to the naive solution
453 // which might have less (?).
454 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000455 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000456 li = layout.begin() + 1, le = layout.end();
457
458 // Look for something that the header end is already
459 // satisfactorily aligned for.
460 for (; li != le && endAlign < li->Alignment; ++li)
461 ;
462
463 // If we found something that's naturally aligned for the end of
464 // the header, keep adding things...
465 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000466 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000467 for (; li != le; ++li) {
468 assert(endAlign >= li->Alignment);
469
470 li->setIndex(info, elementTypes.size());
471 elementTypes.push_back(li->Type);
472 blockSize += li->Size;
473 endAlign = getLowBit(blockSize);
474
475 // ...until we get to the alignment of the maximum field.
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000476 if (endAlign >= maxFieldAlign) {
477 if (li == first) {
478 // No user field was appended. So, a gap was added.
479 // Save total gap size for use in block layout bit map.
480 info.BlockHeaderForcedGapSize = li->Size;
481 }
John McCall6b5a61b2011-02-07 10:33:21 +0000482 break;
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000483 }
John McCall6b5a61b2011-02-07 10:33:21 +0000484 }
John McCall6b5a61b2011-02-07 10:33:21 +0000485 // Don't re-append everything we just appended.
486 layout.erase(first, li);
487 }
488 }
489
John McCall6ea48412012-04-26 21:14:42 +0000490 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanianff685c52012-12-04 17:20:57 +0000491
John McCall6b5a61b2011-02-07 10:33:21 +0000492 // At this point, we just have to add padding if the end align still
493 // isn't aligned right.
494 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000495 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
496 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000497
John McCall5936e332011-02-15 09:22:45 +0000498 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
499 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000500 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000501 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000502 }
503
John McCall6c803f72012-05-01 20:28:00 +0000504 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000505 assert(endAlign == getLowBit(blockSize));
John McCall6b5a61b2011-02-07 10:33:21 +0000506 // Slam everything else on now. This works because they have
507 // strictly decreasing alignment and we expect that size is always a
508 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000510 li = layout.begin(), le = layout.end(); li != le; ++li) {
511 assert(endAlign >= li->Alignment);
512 li->setIndex(info, elementTypes.size());
513 elementTypes.push_back(li->Type);
514 blockSize += li->Size;
515 endAlign = getLowBit(blockSize);
516 }
517
518 info.StructureType =
519 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
520}
521
John McCall1a343eb2011-11-10 08:15:53 +0000522/// Enter the scope of a block. This should be run at the entrance to
523/// a full-expression so that the block's cleanups are pushed at the
524/// right place in the stack.
525static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000526 assert(CGF.HaveInsertPoint());
527
John McCall1a343eb2011-11-10 08:15:53 +0000528 // Allocate the block info and place it at the head of the list.
529 CGBlockInfo &blockInfo =
530 *new CGBlockInfo(block, CGF.CurFn->getName());
531 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
532 CGF.FirstBlockInfo = &blockInfo;
533
534 // Compute information about the layout, etc., of this block,
535 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000536 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000537
538 // Nothing else to do if it can be global.
539 if (blockInfo.CanBeGlobal) return;
540
541 // Make the allocation for the block.
542 blockInfo.Address =
543 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
544 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
545
546 // If there are cleanups to emit, enter them (but inactive).
547 if (!blockInfo.NeedsCopyDispose) return;
548
549 // Walk through the captures (in order) and find the ones not
550 // captured by constant.
551 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
552 ce = block->capture_end(); ci != ce; ++ci) {
553 // Ignore __block captures; there's nothing special in the
554 // on-stack block that we need to do for them.
555 if (ci->isByRef()) continue;
556
557 // Ignore variables that are constant-captured.
558 const VarDecl *variable = ci->getVariable();
559 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
560 if (capture.isConstant()) continue;
561
562 // Ignore objects that aren't destructed.
563 QualType::DestructionKind dtorKind =
564 variable->getType().isDestructedType();
565 if (dtorKind == QualType::DK_none) continue;
566
567 CodeGenFunction::Destroyer *destroyer;
568
569 // Block captures count as local values and have imprecise semantics.
570 // They also can't be arrays, so need to worry about that.
571 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000572 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000573 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000574 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000575 }
576
577 // GEP down to the address.
578 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
579 capture.getIndex());
580
John McCall6f103ba2011-11-10 10:43:54 +0000581 // We can use that GEP as the dominating IP.
582 if (!blockInfo.DominatingIP)
583 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
584
John McCall1a343eb2011-11-10 08:15:53 +0000585 CleanupKind cleanupKind = InactiveNormalCleanup;
586 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
587 if (useArrayEHCleanup)
588 cleanupKind = InactiveNormalAndEHCleanup;
589
590 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000591 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000592
593 // Remember where that cleanup was.
594 capture.setCleanup(CGF.EHStack.stable_begin());
595 }
596}
597
598/// Enter a full-expression with a non-trivial number of objects to
599/// clean up. This is in this file because, at the moment, the only
600/// kind of cleanup object is a BlockDecl*.
601void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
602 assert(E->getNumObjects() != 0);
603 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
604 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
605 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
606 enterBlockScope(*this, *i);
607 }
608}
609
610/// Find the layout for the given block in a linked list and remove it.
611static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
612 const BlockDecl *block) {
613 while (true) {
614 assert(head && *head);
615 CGBlockInfo *cur = *head;
616
617 // If this is the block we're looking for, splice it out of the list.
618 if (cur->getBlockDecl() == block) {
619 *head = cur->NextBlockInfo;
620 return cur;
621 }
622
623 head = &cur->NextBlockInfo;
624 }
625}
626
627/// Destroy a chain of block layouts.
628void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
629 assert(head && "destroying an empty chain");
630 do {
631 CGBlockInfo *cur = head;
632 head = cur->NextBlockInfo;
633 delete cur;
634 } while (head != 0);
635}
636
John McCall6b5a61b2011-02-07 10:33:21 +0000637/// Emit a block literal expression in the current function.
638llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000639 // If the block has no captures, we won't have a pre-computed
640 // layout for it.
641 if (!blockExpr->getBlockDecl()->hasCaptures()) {
642 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000643 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000644 blockInfo.BlockExpression = blockExpr;
645 return EmitBlockLiteral(blockInfo);
646 }
John McCall6b5a61b2011-02-07 10:33:21 +0000647
John McCall1a343eb2011-11-10 08:15:53 +0000648 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000649 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000650 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
651 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000652
John McCall1a343eb2011-11-10 08:15:53 +0000653 blockInfo->BlockExpression = blockExpr;
654 return EmitBlockLiteral(*blockInfo);
655}
656
657llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
658 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000659 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000660 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000661 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000662 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000663 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000664 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000665
666 // If there is nothing to capture, we can emit this as a global block.
667 if (blockInfo.CanBeGlobal)
668 return buildGlobalBlock(CGM, blockInfo, blockFn);
669
670 // Otherwise, we have to emit this as a local block.
671
672 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000673 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000674
675 // Build the block descriptor.
676 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
677
John McCall1a343eb2011-11-10 08:15:53 +0000678 llvm::AllocaInst *blockAddr = blockInfo.Address;
679 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000680
681 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000682 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanianf22ae652012-11-01 18:32:55 +0000683 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall6b5a61b2011-02-07 10:33:21 +0000684 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
685 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000686 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000687
688 // Initialize the block literal.
689 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000690 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000691 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000692 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000693 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
694 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
695 "block.invoke"));
696 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
697 "block.descriptor"));
698
699 // Finally, capture all the values into the block.
700 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
701
702 // First, 'this'.
703 if (blockDecl->capturesCXXThis()) {
704 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
705 blockInfo.CXXThisIndex,
706 "block.captured-this.addr");
707 Builder.CreateStore(LoadCXXThis(), addr);
708 }
709
710 // Next, captured variables.
711 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
712 ce = blockDecl->capture_end(); ci != ce; ++ci) {
713 const VarDecl *variable = ci->getVariable();
714 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
715
716 // Ignore constant captures.
717 if (capture.isConstant()) continue;
718
719 QualType type = variable->getType();
720
721 // This will be a [[type]]*, except that a byref entry will just be
722 // an i8**.
723 llvm::Value *blockField =
724 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
725 "block.captured");
726
727 // Compute the address of the thing we're going to move into the
728 // block literal.
729 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000730 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000731 // We need to use the capture from the enclosing block.
732 const CGBlockInfo::Capture &enclosingCapture =
733 BlockInfo->getCapture(variable);
734
735 // This is a [[type]]*, except that a byref entry wil just be an i8**.
736 src = Builder.CreateStructGEP(LoadBlockStruct(),
737 enclosingCapture.getIndex(),
738 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000739 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000740 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000741 // special; we'll simply emit it directly.
742 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000743 } else {
744 // This is a [[type]]*.
745 src = LocalDeclMap[variable];
746 }
747
748 // For byrefs, we just write the pointer to the byref struct into
749 // the block field. There's no need to chase the forwarding
750 // pointer at this point, since we're building something that will
751 // live a shorter life than the stack byref anyway.
752 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000753 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000754 if (ci->isNested())
755 src = Builder.CreateLoad(src, "byref.capture");
756 else
John McCall5936e332011-02-15 09:22:45 +0000757 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000758
John McCall5936e332011-02-15 09:22:45 +0000759 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000760 Builder.CreateStore(src, blockField);
761
762 // If we have a copy constructor, evaluate that into the block field.
763 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000764 if (blockDecl->isConversionFromLambda()) {
765 // If we have a lambda conversion, emit the expression
766 // directly into the block instead.
767 CharUnits Align = getContext().getTypeAlignInChars(type);
768 AggValueSlot Slot =
769 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
770 AggValueSlot::IsDestructed,
771 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000772 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000773 EmitAggExpr(copyExpr, Slot);
774 } else {
775 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
776 }
John McCall6b5a61b2011-02-07 10:33:21 +0000777
778 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000779 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000780 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
781
782 // Otherwise, fake up a POD copy into the block field.
783 } else {
John McCallf85e1932011-06-15 23:02:42 +0000784 // Fake up a new variable so that EmitScalarInit doesn't think
785 // we're referring to the variable in its own initializer.
786 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000787 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000788
John McCallbb699b02011-02-07 18:37:40 +0000789 // We use one of these or the other depending on whether the
790 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000791 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
792 /*refersToEnclosing*/ ci->isNested(), type,
793 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000794
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000795 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000796 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000797 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000798 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000799 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000800 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000801 }
802
John McCall1a343eb2011-11-10 08:15:53 +0000803 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000804 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000805 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
806 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000807 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000808 }
John McCall6b5a61b2011-02-07 10:33:21 +0000809 }
810
811 // Cast to the converted block-pointer type, which happens (somewhat
812 // unfortunately) to be a pointer to function type.
813 llvm::Value *result =
814 Builder.CreateBitCast(blockAddr,
815 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000816
John McCall6b5a61b2011-02-07 10:33:21 +0000817 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000818}
819
820
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000821llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000822 if (BlockDescriptorType)
823 return BlockDescriptorType;
824
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000825 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000826 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000827
Mike Stumpab695142009-02-13 15:16:56 +0000828 // struct __block_descriptor {
829 // unsigned long reserved;
830 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000831 //
832 // // later, the following will be added
833 //
834 // struct {
835 // void (*copyHelper)();
836 // void (*copyHelper)();
837 // } helpers; // !!! optional
838 //
839 // const char *signature; // the block signature
840 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000841 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000842 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000843 llvm::StructType::create("struct.__block_descriptor",
844 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000845
John McCall6b5a61b2011-02-07 10:33:21 +0000846 // Now form a pointer to that.
847 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000848 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000849}
850
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000851llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000852 if (GenericBlockLiteralType)
853 return GenericBlockLiteralType;
854
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000855 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000856
Mike Stump9b8a7972009-02-13 15:25:34 +0000857 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000858 // void *__isa;
859 // int __flags;
860 // int __reserved;
861 // void (*__invoke)(void *);
862 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000863 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000864 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000865 llvm::StructType::create("struct.__block_literal_generic",
866 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
867 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000868
Mike Stump9b8a7972009-02-13 15:25:34 +0000869 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000870}
871
Mike Stumpbd65cac2009-02-19 01:01:04 +0000872
Anders Carlssona1736c02009-12-24 21:13:40 +0000873RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
874 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000875 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000876 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000877
Anders Carlssonacfde802009-02-12 00:39:25 +0000878 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
879
880 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000881 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000882 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000883
884 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000885 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000886 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
887
888 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000889 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000890
Benjamin Kramer578faa82011-09-27 21:06:10 +0000891 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000892
Anders Carlssonacfde802009-02-12 00:39:25 +0000893 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000894 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000895 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000896
Anders Carlsson782f3972009-04-08 23:13:16 +0000897 QualType FnType = BPT->getPointeeType();
898
Anders Carlssonacfde802009-02-12 00:39:25 +0000899 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000900 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000901 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000902
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000903 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000904 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000905
John McCall64cd2322011-03-09 08:39:33 +0000906 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000907 const CGFunctionInfo &FnInfo =
John McCalle56bb362012-12-07 07:03:17 +0000908 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000910 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000911 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chris Lattner2acc6e32011-07-18 04:24:23 +0000913 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000914 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Anders Carlssonacfde802009-02-12 00:39:25 +0000916 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000917 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000918}
Anders Carlssond5cab542009-02-12 17:55:02 +0000919
John McCall6b5a61b2011-02-07 10:33:21 +0000920llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
921 bool isByRef) {
922 assert(BlockInfo && "evaluating block ref without block information?");
923 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000924
John McCall6b5a61b2011-02-07 10:33:21 +0000925 // Handle constant captures.
926 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000927
John McCall6b5a61b2011-02-07 10:33:21 +0000928 llvm::Value *addr =
929 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
930 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000931
John McCall6b5a61b2011-02-07 10:33:21 +0000932 if (isByRef) {
933 // addr should be a void** right now. Load, then cast the result
934 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000935
John McCall6b5a61b2011-02-07 10:33:21 +0000936 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000937 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000938 = llvm::PointerType::get(BuildByRefType(variable), 0);
939 addr = Builder.CreateBitCast(addr, byrefPointerType,
940 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000941
John McCall6b5a61b2011-02-07 10:33:21 +0000942 // Follow the forwarding pointer.
943 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
944 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000945
John McCall6b5a61b2011-02-07 10:33:21 +0000946 // Cast back to byref* and GEP over to the actual object.
947 addr = Builder.CreateBitCast(addr, byrefPointerType);
948 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
949 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000950 }
951
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000952 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000953 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000954
John McCall6b5a61b2011-02-07 10:33:21 +0000955 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000956}
957
Mike Stump67a64482009-02-14 22:16:35 +0000958llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000959CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000960 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000961 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
962 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000963
John McCall6b5a61b2011-02-07 10:33:21 +0000964 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000965 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000966
John McCall6b5a61b2011-02-07 10:33:21 +0000967 // Using that metadata, generate the actual block function.
968 llvm::Constant *blockFn;
969 {
970 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000971 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
972 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000973 0, LocalDeclMap,
974 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000975 }
John McCall5936e332011-02-15 09:22:45 +0000976 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000977
John McCalld16c2cf2011-02-08 08:22:06 +0000978 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000979}
980
John McCall6b5a61b2011-02-07 10:33:21 +0000981static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
982 const CGBlockInfo &blockInfo,
983 llvm::Constant *blockFn) {
984 assert(blockInfo.CanBeGlobal);
985
986 // Generate the constants for the block literal initializer.
987 llvm::Constant *fields[BlockHeaderSize];
988
989 // isa
990 fields[0] = CGM.getNSConcreteGlobalBlock();
991
992 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000993 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
994 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
995
John McCall5936e332011-02-15 09:22:45 +0000996 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000997
998 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000999 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001000
1001 // Function
1002 fields[3] = blockFn;
1003
1004 // Descriptor
1005 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1006
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001007 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +00001008
1009 llvm::GlobalVariable *literal =
1010 new llvm::GlobalVariable(CGM.getModule(),
1011 init->getType(),
1012 /*constant*/ true,
1013 llvm::GlobalVariable::InternalLinkage,
1014 init,
1015 "__block_literal_global");
1016 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1017
1018 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001019 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001020 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1021 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001022}
1023
Mike Stump00470a12009-03-05 08:32:30 +00001024llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001025CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1026 const CGBlockInfo &blockInfo,
1027 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001028 const DeclMapTy &ldm,
1029 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001030 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001031
Devang Patel6d1155b2011-03-07 21:53:18 +00001032 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001033 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001034 CurGD = GD;
1035
John McCall6b5a61b2011-02-07 10:33:21 +00001036 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Mike Stump7f28a9c2009-03-13 23:34:28 +00001038 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001039 // to be local to this function as well, in case they're directly
1040 // referenced in a block.
1041 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1042 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1043 if (var && !var->hasLocalStorage())
1044 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001045 }
1046
John McCall6b5a61b2011-02-07 10:33:21 +00001047 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001048
John McCall6b5a61b2011-02-07 10:33:21 +00001049 // Build the argument list.
1050 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 // The first argument is the block pointer. Just take it as a void*
1053 // and cast it later.
1054 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001055 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001056
John McCall8178df32011-02-22 22:38:33 +00001057 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1058 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001059 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001060
John McCall6b5a61b2011-02-07 10:33:21 +00001061 // Now add the rest of the parameters.
1062 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1063 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001064 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001065
John McCall6b5a61b2011-02-07 10:33:21 +00001066 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001067 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001068 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001069 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1070 fnType->getExtInfo(),
1071 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001072 if (CGM.ReturnTypeUsesSRet(fnInfo))
1073 blockInfo.UsesStret = true;
1074
John McCallde5d3c72012-02-17 03:33:10 +00001075 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001076
John McCall6b5a61b2011-02-07 10:33:21 +00001077 MangleBuffer name;
1078 CGM.getBlockMangledName(GD, name, blockDecl);
1079 llvm::Function *fn =
1080 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1081 name.getString(), &CGM.getModule());
1082 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001083
John McCall6b5a61b2011-02-07 10:33:21 +00001084 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001085 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001086 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001087 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001088
John McCall8178df32011-02-22 22:38:33 +00001089 // Okay. Undo some of what StartFunction did.
1090
1091 // Pull the 'self' reference out of the local decl map.
1092 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1093 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001094 BlockPointer = Builder.CreateBitCast(blockAddr,
1095 blockInfo.StructureType->getPointerTo(),
1096 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001097
John McCallea1471e2010-05-20 01:18:31 +00001098 // If we have a C++ 'this' reference, go ahead and force it into
1099 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001100 if (blockDecl->capturesCXXThis()) {
1101 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1102 blockInfo.CXXThisIndex,
1103 "block.captured-this");
1104 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001105 }
1106
John McCall6b5a61b2011-02-07 10:33:21 +00001107 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1108 // appease it.
1109 if (const ObjCMethodDecl *method
1110 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1111 const VarDecl *self = method->getSelfDecl();
1112
1113 // There might not be a capture for 'self', but if there is...
1114 if (blockInfo.Captures.count(self)) {
1115 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1116 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1117 capture.getIndex(),
1118 "block.captured-self");
1119 LocalDeclMap[self] = selfAddr;
1120 }
1121 }
1122
1123 // Also force all the constant captures.
1124 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1125 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1126 const VarDecl *variable = ci->getVariable();
1127 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1128 if (!capture.isConstant()) continue;
1129
1130 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1131
1132 llvm::AllocaInst *alloca =
1133 CreateMemTemp(variable->getType(), "block.captured-const");
1134 alloca->setAlignment(align);
1135
1136 Builder.CreateStore(capture.getConstant(), alloca, align);
1137
1138 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001139 }
1140
John McCallf4b88a42012-03-10 09:33:50 +00001141 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001142 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1143 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1144 --entry_ptr;
1145
Eli Friedman64bee652012-02-25 02:48:22 +00001146 if (IsLambdaConversionToBlock)
1147 EmitLambdaBlockInvokeBody();
1148 else
1149 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001150
Mike Stumpde8c5c72009-10-01 00:27:30 +00001151 // Remember where we were...
1152 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001153
Mike Stumpde8c5c72009-10-01 00:27:30 +00001154 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001155 ++entry_ptr;
1156 Builder.SetInsertPoint(entry, entry_ptr);
1157
John McCallf4b88a42012-03-10 09:33:50 +00001158 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001159 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001160 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001161 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1162 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1163 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001164 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001165
Douglas Gregor4cdad312012-10-23 20:05:01 +00001166 if (CGM.getCodeGenOpts().getDebugInfo()
1167 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001168 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1169 if (capture.isConstant()) {
1170 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1171 Builder);
1172 continue;
1173 }
John McCall6b5a61b2011-02-07 10:33:21 +00001174
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001175 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1176 Builder, blockInfo);
1177 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001178 }
Manman Ren3c7a0e12013-01-04 18:51:35 +00001179 // Recover location if it was changed in the above loop.
1180 DI->EmitLocation(Builder,
1181 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stumpb1a6e682009-09-30 02:43:10 +00001182 }
John McCall6b5a61b2011-02-07 10:33:21 +00001183
Mike Stumpde8c5c72009-10-01 00:27:30 +00001184 // And resume where we left off.
1185 if (resume == 0)
1186 Builder.ClearInsertionPoint();
1187 else
1188 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001189
John McCall6b5a61b2011-02-07 10:33:21 +00001190 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001191
John McCall6b5a61b2011-02-07 10:33:21 +00001192 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001193}
Mike Stumpa99038c2009-02-28 09:07:16 +00001194
John McCall6b5a61b2011-02-07 10:33:21 +00001195/*
1196 notes.push_back(HelperInfo());
1197 HelperInfo &note = notes.back();
1198 note.index = capture.getIndex();
1199 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1200 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001201
John McCall6b5a61b2011-02-07 10:33:21 +00001202 if (ci->isByRef()) {
1203 note.flag = BLOCK_FIELD_IS_BYREF;
1204 if (type.isObjCGCWeak())
1205 note.flag |= BLOCK_FIELD_IS_WEAK;
1206 } else if (type->isBlockPointerType()) {
1207 note.flag = BLOCK_FIELD_IS_BLOCK;
1208 } else {
1209 note.flag = BLOCK_FIELD_IS_OBJECT;
1210 }
1211 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001212
Mike Stump00470a12009-03-05 08:32:30 +00001213
Mike Stumpa99038c2009-02-28 09:07:16 +00001214
John McCall6b5a61b2011-02-07 10:33:21 +00001215llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001216CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001217 ASTContext &C = getContext();
1218
1219 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001220 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1221 args.push_back(&dstDecl);
1222 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1223 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Mike Stumpa4f668f2009-03-06 01:33:24 +00001225 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001226 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1227 FunctionType::ExtInfo(),
1228 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001229
John McCall6b5a61b2011-02-07 10:33:21 +00001230 // FIXME: it would be nice if these were mergeable with things with
1231 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001232 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001233
1234 llvm::Function *Fn =
1235 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001236 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001237
1238 IdentifierInfo *II
1239 = &CGM.getContext().Idents.get("__copy_helper_block_");
1240
Devang Patel58dc5ca2011-05-02 20:37:08 +00001241 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001242 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001243
John McCall6b5a61b2011-02-07 10:33:21 +00001244 FunctionDecl *FD = FunctionDecl::Create(C,
1245 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001246 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001247 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001248 SC_Static,
1249 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001250 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001251 false);
John McCalld26bc762011-03-09 04:27:21 +00001252 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001253
Chris Lattner2acc6e32011-07-18 04:24:23 +00001254 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001255
John McCalld26bc762011-03-09 04:27:21 +00001256 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001257 src = Builder.CreateLoad(src);
1258 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001259
John McCalld26bc762011-03-09 04:27:21 +00001260 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001261 dst = Builder.CreateLoad(dst);
1262 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001263
John McCall6b5a61b2011-02-07 10:33:21 +00001264 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001265
John McCall6b5a61b2011-02-07 10:33:21 +00001266 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1267 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1268 const VarDecl *variable = ci->getVariable();
1269 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001270
John McCall6b5a61b2011-02-07 10:33:21 +00001271 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1272 if (capture.isConstant()) continue;
1273
1274 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001275 BlockFieldFlags flags;
1276
John McCall015f33b2012-10-17 02:28:37 +00001277 bool useARCWeakCopy = false;
1278 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001279
1280 if (copyExpr) {
1281 assert(!ci->isByRef());
1282 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001283
John McCall6b5a61b2011-02-07 10:33:21 +00001284 } else if (ci->isByRef()) {
1285 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001286 if (type.isObjCGCWeak())
1287 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001288
John McCallf85e1932011-06-15 23:02:42 +00001289 } else if (type->isObjCRetainableType()) {
1290 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001291 bool isBlockPointer = type->isBlockPointerType();
1292 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001293 flags = BLOCK_FIELD_IS_BLOCK;
1294
1295 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001296 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001297 Qualifiers qs = type.getQualifiers();
1298
John McCall015f33b2012-10-17 02:28:37 +00001299 // We need to register __weak direct captures with the runtime.
1300 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1301 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001302
John McCall015f33b2012-10-17 02:28:37 +00001303 // We need to retain the copied value for __strong direct captures.
1304 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1305 // If it's a block pointer, we have to copy the block and
1306 // assign that to the destination pointer, so we might as
1307 // well use _Block_object_assign. Otherwise we can avoid that.
1308 if (!isBlockPointer)
1309 useARCStrongCopy = true;
1310
1311 // Otherwise the memcpy is fine.
1312 } else {
1313 continue;
1314 }
1315
1316 // Non-ARC captures of retainable pointers are strong and
1317 // therefore require a call to _Block_object_assign.
1318 } else {
1319 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001320 }
1321 } else {
1322 continue;
1323 }
John McCall6b5a61b2011-02-07 10:33:21 +00001324
1325 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001326 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1327 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001328
1329 // If there's an explicit copy expression, we do that.
1330 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001331 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001332 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001333 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001334 } else {
1335 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001336 if (useARCStrongCopy) {
1337 // At -O0, store null into the destination field (so that the
1338 // storeStrong doesn't over-release) and then call storeStrong.
1339 // This is a workaround to not having an initStrong call.
1340 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1341 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1342 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1343 Builder.CreateStore(null, dstField);
1344 EmitARCStoreStrongCall(dstField, srcValue, true);
1345
1346 // With optimization enabled, take advantage of the fact that
1347 // the blocks runtime guarantees a memcpy of the block data, and
1348 // just emit a retain of the src field.
1349 } else {
1350 EmitARCRetainNonBlock(srcValue);
1351
1352 // We don't need this anymore, so kill it. It's not quite
1353 // worth the annoyance to avoid creating it in the first place.
1354 cast<llvm::Instruction>(dstField)->eraseFromParent();
1355 }
1356 } else {
1357 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1358 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1359 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1360 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1361 }
Mike Stump08920992009-03-07 02:35:30 +00001362 }
1363 }
1364
John McCalld16c2cf2011-02-08 08:22:06 +00001365 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001366
John McCall5936e332011-02-15 09:22:45 +00001367 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001368}
1369
John McCall6b5a61b2011-02-07 10:33:21 +00001370llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001371CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001372 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001373
John McCall6b5a61b2011-02-07 10:33:21 +00001374 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001375 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1376 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Mike Stumpa4f668f2009-03-06 01:33:24 +00001378 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001379 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1380 FunctionType::ExtInfo(),
1381 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001382
Mike Stump3899a7f2009-06-05 23:26:36 +00001383 // FIXME: We'd like to put these into a mergable by content, with
1384 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001385 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001386
1387 llvm::Function *Fn =
1388 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001389 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001390
Devang Patel58dc5ca2011-05-02 20:37:08 +00001391 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001392 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001393
Mike Stumpa4f668f2009-03-06 01:33:24 +00001394 IdentifierInfo *II
1395 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1396
John McCall6b5a61b2011-02-07 10:33:21 +00001397 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001398 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001399 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001400 SC_Static,
1401 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001402 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001403 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001404
Chris Lattner2acc6e32011-07-18 04:24:23 +00001405 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001406
John McCalld26bc762011-03-09 04:27:21 +00001407 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001408 src = Builder.CreateLoad(src);
1409 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001410
John McCall6b5a61b2011-02-07 10:33:21 +00001411 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1412
John McCalld16c2cf2011-02-08 08:22:06 +00001413 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001414
1415 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1416 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1417 const VarDecl *variable = ci->getVariable();
1418 QualType type = variable->getType();
1419
1420 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1421 if (capture.isConstant()) continue;
1422
John McCalld16c2cf2011-02-08 08:22:06 +00001423 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001424 const CXXDestructorDecl *dtor = 0;
1425
John McCall015f33b2012-10-17 02:28:37 +00001426 bool useARCWeakDestroy = false;
1427 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001428
John McCall6b5a61b2011-02-07 10:33:21 +00001429 if (ci->isByRef()) {
1430 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001431 if (type.isObjCGCWeak())
1432 flags |= BLOCK_FIELD_IS_WEAK;
1433 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1434 if (record->hasTrivialDestructor())
1435 continue;
1436 dtor = record->getDestructor();
1437 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001438 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001439 if (type->isBlockPointerType())
1440 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001441
John McCallf85e1932011-06-15 23:02:42 +00001442 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001443 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001444 Qualifiers qs = type.getQualifiers();
1445
1446 // Don't generate special dispose logic for a captured object
1447 // unless it's __strong or __weak.
1448 if (!qs.hasStrongOrWeakObjCLifetime())
1449 continue;
1450
1451 // Support __weak direct captures.
1452 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001453 useARCWeakDestroy = true;
1454
1455 // Tools really want us to use objc_storeStrong here.
1456 else
1457 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001458 }
1459 } else {
1460 continue;
1461 }
John McCall6b5a61b2011-02-07 10:33:21 +00001462
1463 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001464 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001465
1466 // If there's an explicit copy expression, we do that.
1467 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001468 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001469
John McCallf85e1932011-06-15 23:02:42 +00001470 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001471 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001472 EmitARCDestroyWeak(srcField);
1473
John McCall015f33b2012-10-17 02:28:37 +00001474 // Destroy strong objects with a call if requested.
1475 } else if (useARCStrongDestroy) {
1476 EmitARCDestroyStrong(srcField, /*precise*/ false);
1477
John McCall6b5a61b2011-02-07 10:33:21 +00001478 // Otherwise we call _Block_object_dispose. It wouldn't be too
1479 // hard to just emit this as a cleanup if we wanted to make sure
1480 // that things were done in reverse.
1481 } else {
1482 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001483 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001484 BuildBlockRelease(value, flags);
1485 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001486 }
1487
John McCall6b5a61b2011-02-07 10:33:21 +00001488 cleanups.ForceCleanup();
1489
John McCalld16c2cf2011-02-08 08:22:06 +00001490 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001491
John McCall5936e332011-02-15 09:22:45 +00001492 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001493}
1494
John McCallf0c11f72011-03-31 08:03:29 +00001495namespace {
1496
1497/// Emits the copy/dispose helper functions for a __block object of id type.
1498class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1499 BlockFieldFlags Flags;
1500
1501public:
1502 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1503 : ByrefHelpers(alignment), Flags(flags) {}
1504
John McCall36170192011-03-31 09:19:20 +00001505 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1506 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001507 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1508
1509 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1510 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1511
1512 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1513
1514 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1515 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1516 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1517 }
1518
1519 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1520 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1521 llvm::Value *value = CGF.Builder.CreateLoad(field);
1522
1523 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1524 }
1525
1526 void profileImpl(llvm::FoldingSetNodeID &id) const {
1527 id.AddInteger(Flags.getBitMask());
1528 }
1529};
1530
John McCallf85e1932011-06-15 23:02:42 +00001531/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1532class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1533public:
1534 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1535
1536 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1537 llvm::Value *srcField) {
1538 CGF.EmitARCMoveWeak(destField, srcField);
1539 }
1540
1541 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1542 CGF.EmitARCDestroyWeak(field);
1543 }
1544
1545 void profileImpl(llvm::FoldingSetNodeID &id) const {
1546 // 0 is distinguishable from all pointers and byref flags
1547 id.AddInteger(0);
1548 }
1549};
1550
1551/// Emits the copy/dispose helpers for an ARC __block __strong variable
1552/// that's not of block-pointer type.
1553class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1554public:
1555 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1556
1557 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1558 llvm::Value *srcField) {
1559 // Do a "move" by copying the value and then zeroing out the old
1560 // variable.
1561
John McCalla59e4b72011-11-09 03:17:26 +00001562 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1563 value->setAlignment(Alignment.getQuantity());
1564
John McCallf85e1932011-06-15 23:02:42 +00001565 llvm::Value *null =
1566 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001567
1568 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1569 store->setAlignment(Alignment.getQuantity());
1570
1571 store = CGF.Builder.CreateStore(null, srcField);
1572 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001573 }
1574
1575 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001576 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001577 }
1578
1579 void profileImpl(llvm::FoldingSetNodeID &id) const {
1580 // 1 is distinguishable from all pointers and byref flags
1581 id.AddInteger(1);
1582 }
1583};
1584
John McCalla59e4b72011-11-09 03:17:26 +00001585/// Emits the copy/dispose helpers for an ARC __block __strong
1586/// variable that's of block-pointer type.
1587class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1588public:
1589 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1590
1591 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1592 llvm::Value *srcField) {
1593 // Do the copy with objc_retainBlock; that's all that
1594 // _Block_object_assign would do anyway, and we'd have to pass the
1595 // right arguments to make sure it doesn't get no-op'ed.
1596 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1597 oldValue->setAlignment(Alignment.getQuantity());
1598
1599 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1600
1601 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1602 store->setAlignment(Alignment.getQuantity());
1603 }
1604
1605 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001606 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001607 }
1608
1609 void profileImpl(llvm::FoldingSetNodeID &id) const {
1610 // 2 is distinguishable from all pointers and byref flags
1611 id.AddInteger(2);
1612 }
1613};
1614
John McCallf0c11f72011-03-31 08:03:29 +00001615/// Emits the copy/dispose helpers for a __block variable with a
1616/// nontrivial copy constructor or destructor.
1617class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1618 QualType VarType;
1619 const Expr *CopyExpr;
1620
1621public:
1622 CXXByrefHelpers(CharUnits alignment, QualType type,
1623 const Expr *copyExpr)
1624 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1625
1626 bool needsCopy() const { return CopyExpr != 0; }
1627 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1628 llvm::Value *srcField) {
1629 if (!CopyExpr) return;
1630 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1631 }
1632
1633 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1634 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1635 CGF.PushDestructorCleanup(VarType, field);
1636 CGF.PopCleanupBlocks(cleanupDepth);
1637 }
1638
1639 void profileImpl(llvm::FoldingSetNodeID &id) const {
1640 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1641 }
1642};
1643} // end anonymous namespace
1644
1645static llvm::Constant *
1646generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001647 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001648 CodeGenModule::ByrefHelpers &byrefInfo) {
1649 ASTContext &Context = CGF.getContext();
1650
1651 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001652
John McCalld26bc762011-03-09 04:27:21 +00001653 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001654 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001655 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001656
John McCallf0c11f72011-03-31 08:03:29 +00001657 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001658 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Mike Stump45031c02009-03-06 02:29:21 +00001660 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001661 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1662 FunctionType::ExtInfo(),
1663 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001664
John McCallf0c11f72011-03-31 08:03:29 +00001665 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001666 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001667
Mike Stump3899a7f2009-06-05 23:26:36 +00001668 // FIXME: We'd like to put these into a mergable by content, with
1669 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001670 llvm::Function *Fn =
1671 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001672 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001673
1674 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001675 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001676
John McCallf0c11f72011-03-31 08:03:29 +00001677 FunctionDecl *FD = FunctionDecl::Create(Context,
1678 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001679 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001680 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001681 SC_Static,
1682 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001683 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001684
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001685 // Initialize debug info if necessary.
1686 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001687 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001688
John McCallf0c11f72011-03-31 08:03:29 +00001689 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001690 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001691
John McCallf0c11f72011-03-31 08:03:29 +00001692 // dst->x
1693 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1694 destField = CGF.Builder.CreateLoad(destField);
1695 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1696 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001697
John McCallf0c11f72011-03-31 08:03:29 +00001698 // src->x
1699 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1700 srcField = CGF.Builder.CreateLoad(srcField);
1701 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1702 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1703
1704 byrefInfo.emitCopy(CGF, destField, srcField);
1705 }
1706
1707 CGF.FinishFunction();
1708
1709 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001710}
1711
John McCallf0c11f72011-03-31 08:03:29 +00001712/// Build the copy helper for a __block variable.
1713static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001714 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001715 CodeGenModule::ByrefHelpers &info) {
1716 CodeGenFunction CGF(CGM);
1717 return generateByrefCopyHelper(CGF, byrefType, info);
1718}
1719
1720/// Generate code for a __block variable's dispose helper.
1721static llvm::Constant *
1722generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001723 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001724 CodeGenModule::ByrefHelpers &byrefInfo) {
1725 ASTContext &Context = CGF.getContext();
1726 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001727
John McCalld26bc762011-03-09 04:27:21 +00001728 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001729 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001730 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Mike Stump45031c02009-03-06 02:29:21 +00001732 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001733 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1734 FunctionType::ExtInfo(),
1735 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001736
John McCallf0c11f72011-03-31 08:03:29 +00001737 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001738 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001739
Mike Stump3899a7f2009-06-05 23:26:36 +00001740 // FIXME: We'd like to put these into a mergable by content, with
1741 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001742 llvm::Function *Fn =
1743 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001744 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001745 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001746
1747 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001748 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001749
John McCallf0c11f72011-03-31 08:03:29 +00001750 FunctionDecl *FD = FunctionDecl::Create(Context,
1751 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001752 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001753 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001754 SC_Static,
1755 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001756 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001757 // Initialize debug info if necessary.
1758 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001759 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001760
John McCallf0c11f72011-03-31 08:03:29 +00001761 if (byrefInfo.needsDispose()) {
1762 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1763 V = CGF.Builder.CreateLoad(V);
1764 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1765 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001766
John McCallf0c11f72011-03-31 08:03:29 +00001767 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001768 }
Mike Stump45031c02009-03-06 02:29:21 +00001769
John McCallf0c11f72011-03-31 08:03:29 +00001770 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001771
John McCallf0c11f72011-03-31 08:03:29 +00001772 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001773}
1774
John McCallf0c11f72011-03-31 08:03:29 +00001775/// Build the dispose helper for a __block variable.
1776static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001777 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001778 CodeGenModule::ByrefHelpers &info) {
1779 CodeGenFunction CGF(CGM);
1780 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001781}
1782
John McCallf0c11f72011-03-31 08:03:29 +00001783///
1784template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001785 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001786 T &byrefInfo) {
1787 // Increase the field's alignment to be at least pointer alignment,
1788 // since the layout of the byref struct will guarantee at least that.
1789 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1790 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1791
1792 llvm::FoldingSetNodeID id;
1793 byrefInfo.Profile(id);
1794
1795 void *insertPos;
1796 CodeGenModule::ByrefHelpers *node
1797 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1798 if (node) return static_cast<T*>(node);
1799
1800 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1801 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1802
1803 T *copy = new (CGM.getContext()) T(byrefInfo);
1804 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1805 return copy;
1806}
1807
1808CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001809CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001810 const AutoVarEmission &emission) {
1811 const VarDecl &var = *emission.Variable;
1812 QualType type = var.getType();
1813
1814 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1815 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1816 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1817
1818 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1819 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1820 }
1821
John McCallf85e1932011-06-15 23:02:42 +00001822 // Otherwise, if we don't have a retainable type, there's nothing to do.
1823 // that the runtime does extra copies.
1824 if (!type->isObjCRetainableType()) return 0;
1825
1826 Qualifiers qs = type.getQualifiers();
1827
1828 // If we have lifetime, that dominates.
1829 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001830 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001831
1832 switch (lifetime) {
1833 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1834
1835 // These are just bits as far as the runtime is concerned.
1836 case Qualifiers::OCL_ExplicitNone:
1837 case Qualifiers::OCL_Autoreleasing:
1838 return 0;
1839
1840 // Tell the runtime that this is ARC __weak, called by the
1841 // byref routines.
1842 case Qualifiers::OCL_Weak: {
1843 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1844 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1845 }
1846
1847 // ARC __strong __block variables need to be retained.
1848 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001849 // Block pointers need to be copied, and there's no direct
1850 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001851 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001852 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001853 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1854
1855 // Otherwise, we transfer ownership of the retain from the stack
1856 // to the heap.
1857 } else {
1858 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1859 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1860 }
1861 }
1862 llvm_unreachable("fell out of lifetime switch!");
1863 }
1864
John McCallf0c11f72011-03-31 08:03:29 +00001865 BlockFieldFlags flags;
1866 if (type->isBlockPointerType()) {
1867 flags |= BLOCK_FIELD_IS_BLOCK;
1868 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1869 type->isObjCObjectPointerType()) {
1870 flags |= BLOCK_FIELD_IS_OBJECT;
1871 } else {
1872 return 0;
1873 }
1874
1875 if (type.isObjCGCWeak())
1876 flags |= BLOCK_FIELD_IS_WEAK;
1877
1878 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1879 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001880}
1881
John McCall5af02db2011-03-31 01:59:53 +00001882unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1883 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1884
1885 return ByRefValueInfo.find(VD)->second.second;
1886}
1887
1888llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1889 const VarDecl *V) {
1890 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1891 Loc = Builder.CreateLoad(Loc);
1892 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1893 V->getNameAsString());
1894 return Loc;
1895}
1896
1897/// BuildByRefType - This routine changes a __block variable declared as T x
1898/// into:
1899///
1900/// struct {
1901/// void *__isa;
1902/// void *__forwarding;
1903/// int32_t __flags;
1904/// int32_t __size;
1905/// void *__copy_helper; // only if needed
1906/// void *__destroy_helper; // only if needed
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001907/// void *__byref_variable_layout;// only if needed
John McCall5af02db2011-03-31 01:59:53 +00001908/// char padding[X]; // only if needed
1909/// T x;
1910/// } x
1911///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001912llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1913 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001914 if (Info.first)
1915 return Info.first;
1916
1917 QualType Ty = D->getType();
1918
Chris Lattner5f9e2722011-07-23 10:55:15 +00001919 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001920
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001921 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001922 llvm::StructType::create(getLLVMContext(),
1923 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001924
1925 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001926 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001927
1928 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001929 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001930
1931 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001932 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001933
1934 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001935 types.push_back(Int32Ty);
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00001936 // Note that this must match *exactly* the logic in buildByrefHelpers.
1937 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall5af02db2011-03-31 01:59:53 +00001938 if (HasCopyAndDispose) {
1939 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001940 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001941
1942 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001943 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001944 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001945 bool HasByrefExtendedLayout = false;
1946 Qualifiers::ObjCLifetime Lifetime;
1947 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
1948 HasByrefExtendedLayout)
1949 /// void *__byref_variable_layout;
1950 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001951
1952 bool Packed = false;
1953 CharUnits Align = getContext().getDeclAlign(D);
1954 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1955 // We have to insert padding.
1956
1957 // The struct above has 2 32-bit integers.
1958 unsigned CurrentOffsetInBytes = 4 * 2;
1959
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00001960 // And either 2, 3, 4 or 5 pointers.
1961 unsigned noPointers = 2;
1962 if (HasCopyAndDispose)
1963 noPointers += 2;
1964 if (HasByrefExtendedLayout)
1965 noPointers += 1;
1966
1967 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001968
1969 // Align the offset.
1970 unsigned AlignedOffsetInBytes =
1971 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1972
1973 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1974 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001975 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001976 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001977 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001978 if (NumPaddingBytes > 1)
1979 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1980
John McCall0774cb82011-05-15 01:53:33 +00001981 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001982
1983 // We want a packed struct.
1984 Packed = true;
1985 }
1986 }
1987
1988 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001989 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001990
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001991 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001992
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001993 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001994
John McCall0774cb82011-05-15 01:53:33 +00001995 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001996
1997 return Info.first;
1998}
1999
2000/// Initialize the structural components of a __block variable, i.e.
2001/// everything but the actual object.
2002void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00002003 // Find the address of the local.
2004 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00002005
John McCallf0c11f72011-03-31 08:03:29 +00002006 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002007 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00002008 cast<llvm::PointerType>(addr->getType())->getElementType());
2009
2010 // Build the byref helpers if necessary. This is null if we don't need any.
2011 CodeGenModule::ByrefHelpers *helpers =
2012 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00002013
2014 const VarDecl &D = *emission.Variable;
2015 QualType type = D.getType();
2016
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002017 bool HasByrefExtendedLayout;
2018 Qualifiers::ObjCLifetime ByrefLifetime;
2019 bool ByRefHasLifetime =
2020 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2021
John McCallf0c11f72011-03-31 08:03:29 +00002022 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00002023
2024 // Initialize the 'isa', which is just 0 or 1.
2025 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00002026 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00002027 isa = 1;
2028 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
2029 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
2030
2031 // Store the address of the variable into its own forwarding pointer.
2032 Builder.CreateStore(addr,
2033 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2034
2035 // Blocks ABI:
2036 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002037 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall5af02db2011-03-31 01:59:53 +00002038 BlockFlags flags;
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002039 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2040 if (ByRefHasLifetime) {
2041 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2042 else switch (ByrefLifetime) {
2043 case Qualifiers::OCL_Strong:
2044 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2045 break;
2046 case Qualifiers::OCL_Weak:
2047 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2048 break;
2049 case Qualifiers::OCL_ExplicitNone:
2050 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2051 break;
2052 case Qualifiers::OCL_None:
2053 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2054 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2055 break;
2056 default:
2057 break;
2058 }
2059 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2060 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2061 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2062 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2063 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2064 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2065 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2066 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2067 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2068 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2069 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2070 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2071 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2072 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2073 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2074 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2075 }
2076 printf("\n");
2077 }
2078 }
2079
John McCall5af02db2011-03-31 01:59:53 +00002080 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2081 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2082
John McCallf0c11f72011-03-31 08:03:29 +00002083 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2084 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002085 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2086
John McCallf0c11f72011-03-31 08:03:29 +00002087 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002088 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002089 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002090
2091 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002092 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002093 }
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00002094 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2095 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2096 llvm::Value *ByrefInfoAddr = Builder.CreateStructGEP(addr, helpers ? 6 : 4,
2097 "byref.layout");
2098 // cast destination to pointer to source type.
2099 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2100 DesTy = DesTy->getPointerTo();
2101 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2102 Builder.CreateStore(ByrefLayoutInfo, BC);
2103 }
John McCall5af02db2011-03-31 01:59:53 +00002104}
2105
John McCalld16c2cf2011-02-08 08:22:06 +00002106void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002107 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002108 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002109 V = Builder.CreateBitCast(V, Int8PtrTy);
2110 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002111 Builder.CreateCall2(F, V, N);
2112}
John McCall5af02db2011-03-31 01:59:53 +00002113
2114namespace {
2115 struct CallBlockRelease : EHScopeStack::Cleanup {
2116 llvm::Value *Addr;
2117 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2118
John McCallad346f42011-07-12 20:27:29 +00002119 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002120 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002121 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2122 }
2123 };
2124}
2125
2126/// Enter a cleanup to destroy a __block variable. Note that this
2127/// cleanup should be a no-op if the variable hasn't left the stack
2128/// yet; if a cleanup is required for the variable itself, that needs
2129/// to be done externally.
2130void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2131 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002132 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002133 return;
2134
2135 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2136}
John McCall13db5cf2011-09-09 20:41:01 +00002137
2138/// Adjust the declaration of something from the blocks API.
2139static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2140 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002141 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002142
2143 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2144 if (GV->isDeclaration() &&
2145 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2146 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2147}
2148
2149llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2150 if (BlockObjectDispose)
2151 return BlockObjectDispose;
2152
2153 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2154 llvm::FunctionType *fty
2155 = llvm::FunctionType::get(VoidTy, args, false);
2156 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2157 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2158 return BlockObjectDispose;
2159}
2160
2161llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2162 if (BlockObjectAssign)
2163 return BlockObjectAssign;
2164
2165 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2166 llvm::FunctionType *fty
2167 = llvm::FunctionType::get(VoidTy, args, false);
2168 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2169 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2170 return BlockObjectAssign;
2171}
2172
2173llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2174 if (NSConcreteGlobalBlock)
2175 return NSConcreteGlobalBlock;
2176
2177 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2178 Int8PtrTy->getPointerTo(), 0);
2179 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2180 return NSConcreteGlobalBlock;
2181}
2182
2183llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2184 if (NSConcreteStackBlock)
2185 return NSConcreteStackBlock;
2186
2187 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2188 Int8PtrTy->getPointerTo(), 0);
2189 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2190 return NSConcreteStackBlock;
2191}