blob: 3e126f850514e577095151c6f9e66c2643ea12bb [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
John McCalld16c2cf2011-02-08 08:22:06 +000018#include "CGBlocks.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000020#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Micah Villmow25a6a842012-10-08 16:25:52 +000022#include "llvm/DataLayout.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000023#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000024
Anders Carlssonacfde802009-02-12 00:39:25 +000025using namespace clang;
26using namespace CodeGen;
27
John McCall1a343eb2011-11-10 08:15:53 +000028CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
29 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
John McCall6f103ba2011-11-10 10:43:54 +000030 HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
31 DominatingIP(0) {
John McCallee504292010-05-21 04:11:14 +000032
John McCall1a343eb2011-11-10 08:15:53 +000033 // Skip asm prefix, if any. 'name' is usually taken directly from
34 // the mangled name of the enclosing function.
35 if (!name.empty() && name[0] == '\01')
36 name = name.substr(1);
John McCallee504292010-05-21 04:11:14 +000037}
38
John McCallf0c11f72011-03-31 08:03:29 +000039// Anchor the vtable to this translation unit.
40CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
41
John McCall6b5a61b2011-02-07 10:33:21 +000042/// Build the given block as a global block.
43static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
44 const CGBlockInfo &blockInfo,
45 llvm::Constant *blockFn);
John McCallee504292010-05-21 04:11:14 +000046
John McCall6b5a61b2011-02-07 10:33:21 +000047/// Build the helper function to copy a block.
48static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
49 const CGBlockInfo &blockInfo) {
50 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
51}
52
53/// Build the helper function to dipose of a block.
54static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
55 const CGBlockInfo &blockInfo) {
56 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
57}
58
Fariborz Jahanianaf879c02012-10-25 18:06:53 +000059/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
60/// buildBlockDescriptor is accessed from 5th field of the Block_literal
61/// meta-data and contains stationary information about the block literal.
62/// Its definition will have 4 (or optinally 6) words.
63/// struct Block_descriptor {
64/// unsigned long reserved;
65/// unsigned long size; // size of Block_literal metadata in bytes.
66/// void *copy_func_helper_decl; // optional copy helper.
67/// void *destroy_func_decl; // optioanl destructor helper.
68/// void *block_method_encoding_address;//@encode for block literal signature.
69/// void *block_layout_info; // encoding of captured block variables.
70/// };
John McCall6b5a61b2011-02-07 10:33:21 +000071static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
72 const CGBlockInfo &blockInfo) {
73 ASTContext &C = CGM.getContext();
74
Chris Lattner2acc6e32011-07-18 04:24:23 +000075 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
76 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +000077
Chris Lattner5f9e2722011-07-23 10:55:15 +000078 SmallVector<llvm::Constant*, 6> elements;
Mike Stumpe5fee252009-02-13 16:19:19 +000079
80 // reserved
John McCall6b5a61b2011-02-07 10:33:21 +000081 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stumpe5fee252009-02-13 16:19:19 +000082
83 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000084 // FIXME: What is the right way to say this doesn't fit? We should give
85 // a user diagnostic in that case. Better fix would be to change the
86 // API to size_t.
John McCall6b5a61b2011-02-07 10:33:21 +000087 elements.push_back(llvm::ConstantInt::get(ulong,
88 blockInfo.BlockSize.getQuantity()));
Mike Stumpe5fee252009-02-13 16:19:19 +000089
John McCall6b5a61b2011-02-07 10:33:21 +000090 // Optional copy/dispose helpers.
91 if (blockInfo.NeedsCopyDispose) {
Mike Stumpe5fee252009-02-13 16:19:19 +000092 // copy_func_helper_decl
John McCall6b5a61b2011-02-07 10:33:21 +000093 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000094
95 // destroy_func_decl
John McCall6b5a61b2011-02-07 10:33:21 +000096 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stumpe5fee252009-02-13 16:19:19 +000097 }
98
John McCall6b5a61b2011-02-07 10:33:21 +000099 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
100 std::string typeAtEncoding =
101 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
102 elements.push_back(llvm::ConstantExpr::getBitCast(
103 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000104
John McCall6b5a61b2011-02-07 10:33:21 +0000105 // GC layout.
David Blaikie4e4d0842012-03-11 07:00:24 +0000106 if (C.getLangOpts().ObjC1)
John McCall6b5a61b2011-02-07 10:33:21 +0000107 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
108 else
109 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000110
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000111 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000112
John McCall6b5a61b2011-02-07 10:33:21 +0000113 llvm::GlobalVariable *global =
114 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
115 llvm::GlobalValue::InternalLinkage,
116 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000117
John McCall6b5a61b2011-02-07 10:33:21 +0000118 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000119}
120
John McCall6b5a61b2011-02-07 10:33:21 +0000121/*
122 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000123
John McCall6b5a61b2011-02-07 10:33:21 +0000124 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
125 struct Block_literal {
126 /// Initialized to one of:
127 /// extern void *_NSConcreteStackBlock[];
128 /// extern void *_NSConcreteGlobalBlock[];
129 ///
130 /// In theory, we could start one off malloc'ed by setting
131 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
132 /// this isa:
133 /// extern void *_NSConcreteMallocBlock[];
134 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000135
John McCall6b5a61b2011-02-07 10:33:21 +0000136 /// These are the flags (with corresponding bit number) that the
137 /// compiler is actually supposed to know about.
138 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
139 /// descriptor provides copy and dispose helper functions
140 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
141 /// object with a nontrivial destructor or copy constructor
142 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
143 /// as global memory
144 /// 29. BLOCK_USE_STRET - indicates that the block function
145 /// uses stret, which objc_msgSend needs to know about
146 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
147 /// @encoded signature string
148 /// And we're not supposed to manipulate these:
149 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
150 /// to malloc'ed memory
151 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
152 /// to GC-allocated memory
153 /// Additionally, the bottom 16 bits are a reference count which
154 /// should be zero on the stack.
155 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000156
John McCall6b5a61b2011-02-07 10:33:21 +0000157 /// Reserved; should be zero-initialized.
158 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000159
John McCall6b5a61b2011-02-07 10:33:21 +0000160 /// Function pointer generated from block literal.
161 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000162
John McCall6b5a61b2011-02-07 10:33:21 +0000163 /// Block description metadata generated from block literal.
164 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000165
John McCall6b5a61b2011-02-07 10:33:21 +0000166 /// Captured values follow.
167 _CapturesTypes captures...;
168 };
169 */
David Chisnall5e530af2009-11-17 19:33:30 +0000170
John McCall6b5a61b2011-02-07 10:33:21 +0000171/// The number of fields in a block header.
172const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000173
John McCall6b5a61b2011-02-07 10:33:21 +0000174namespace {
175 /// A chunk of data that we actually have to capture in the block.
176 struct BlockLayoutChunk {
177 CharUnits Alignment;
178 CharUnits Size;
179 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000180 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000181
John McCall6b5a61b2011-02-07 10:33:21 +0000182 BlockLayoutChunk(CharUnits align, CharUnits size,
183 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000184 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000185 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000186
John McCall6b5a61b2011-02-07 10:33:21 +0000187 /// Tell the block info that this chunk has the given field index.
188 void setIndex(CGBlockInfo &info, unsigned index) {
189 if (!Capture)
190 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000191 else
John McCall6b5a61b2011-02-07 10:33:21 +0000192 info.Captures[Capture->getVariable()]
193 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000194 }
John McCall6b5a61b2011-02-07 10:33:21 +0000195 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000196
John McCall6b5a61b2011-02-07 10:33:21 +0000197 /// Order by descending alignment.
198 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
199 return left.Alignment > right.Alignment;
200 }
201}
202
John McCall461c9c12011-02-08 03:07:00 +0000203/// Determines if the given type is safe for constant capture in C++.
204static bool isSafeForCXXConstantCapture(QualType type) {
205 const RecordType *recordType =
206 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
207
208 // Only records can be unsafe.
209 if (!recordType) return true;
210
211 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
212
213 // Maintain semantics for classes with non-trivial dtors or copy ctors.
214 if (!record->hasTrivialDestructor()) return false;
215 if (!record->hasTrivialCopyConstructor()) return false;
216
217 // Otherwise, we just have to make sure there aren't any mutable
218 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000219 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000220}
221
John McCall6b5a61b2011-02-07 10:33:21 +0000222/// It is illegal to modify a const object after initialization.
223/// Therefore, if a const object has a constant initializer, we don't
224/// actually need to keep storage for it in the block; we'll just
225/// rematerialize it at the start of the block function. This is
226/// acceptable because we make no promises about address stability of
227/// captured variables.
228static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000229 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000230 const VarDecl *var) {
231 QualType type = var->getType();
232
233 // We can only do this if the variable is const.
234 if (!type.isConstQualified()) return 0;
235
John McCall461c9c12011-02-08 03:07:00 +0000236 // Furthermore, in C++ we have to worry about mutable fields:
237 // C++ [dcl.type.cv]p4:
238 // Except that any class member declared mutable can be
239 // modified, any attempt to modify a const object during its
240 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000241 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000242 return 0;
243
244 // If the variable doesn't have any initializer (shouldn't this be
245 // invalid?), it's not clear what we should do. Maybe capture as
246 // zero?
247 const Expr *init = var->getInit();
248 if (!init) return 0;
249
Richard Smith2d6a5672012-01-14 04:30:29 +0000250 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000251}
252
253/// Get the low bit of a nonzero character count. This is the
254/// alignment of the nth byte if the 0th byte is universally aligned.
255static CharUnits getLowBit(CharUnits v) {
256 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
257}
258
259static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000260 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000261 ASTContext &C = CGM.getContext();
262
263 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
264 CharUnits ptrSize, ptrAlign, intSize, intAlign;
265 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
266 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
267
268 // Are there crazy embedded platforms where this isn't true?
269 assert(intSize <= ptrSize && "layout assumptions horribly violated");
270
271 CharUnits headerSize = ptrSize;
272 if (2 * intSize < ptrAlign) headerSize += ptrSize;
273 else headerSize += 2 * intSize;
274 headerSize += 2 * ptrSize;
275
276 info.BlockAlign = ptrAlign;
277 info.BlockSize = headerSize;
278
279 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000280 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
281 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000282 elementTypes.push_back(i8p);
283 elementTypes.push_back(intTy);
284 elementTypes.push_back(intTy);
285 elementTypes.push_back(i8p);
286 elementTypes.push_back(CGM.getBlockDescriptorType());
287
288 assert(elementTypes.size() == BlockHeaderSize);
289}
290
291/// Compute the layout of the given block. Attempts to lay the block
292/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000293static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
294 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000295 ASTContext &C = CGM.getContext();
296 const BlockDecl *block = info.getBlockDecl();
297
Chris Lattner5f9e2722011-07-23 10:55:15 +0000298 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000299 initializeForBlockHeader(CGM, info, elementTypes);
300
301 if (!block->hasCaptures()) {
302 info.StructureType =
303 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
304 info.CanBeGlobal = true;
305 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000306 }
Mike Stump00470a12009-03-05 08:32:30 +0000307
John McCall6b5a61b2011-02-07 10:33:21 +0000308 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000309 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000310 layout.reserve(block->capturesCXXThis() +
311 (block->capture_end() - block->capture_begin()));
312
313 CharUnits maxFieldAlign;
314
315 // First, 'this'.
316 if (block->capturesCXXThis()) {
317 const DeclContext *DC = block->getDeclContext();
318 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
319 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000320 QualType thisType;
321 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
322 thisType = C.getPointerType(C.getRecordType(RD));
323 else
324 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000325
Jay Foadef6de3d2011-07-11 09:56:20 +0000326 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000327 std::pair<CharUnits,CharUnits> tinfo
328 = CGM.getContext().getTypeInfoInChars(thisType);
329 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
330
331 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
332 }
333
334 // Next, all the block captures.
335 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
336 ce = block->capture_end(); ci != ce; ++ci) {
337 const VarDecl *variable = ci->getVariable();
338
339 if (ci->isByRef()) {
340 // We have to copy/dispose of the __block reference.
341 info.NeedsCopyDispose = true;
342
John McCall6b5a61b2011-02-07 10:33:21 +0000343 // Just use void* instead of a pointer to the byref type.
344 QualType byRefPtrTy = C.VoidPtrTy;
345
Jay Foadef6de3d2011-07-11 09:56:20 +0000346 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000347 std::pair<CharUnits,CharUnits> tinfo
348 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
349 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
350
351 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
352 &*ci, llvmType));
353 continue;
354 }
355
356 // Otherwise, build a layout chunk with the size and alignment of
357 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000358 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000359 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
360 continue;
361 }
362
John McCallf85e1932011-06-15 23:02:42 +0000363 // If we have a lifetime qualifier, honor it for capture purposes.
364 // That includes *not* copying it if it's __unsafe_unretained.
365 if (Qualifiers::ObjCLifetime lifetime
366 = variable->getType().getObjCLifetime()) {
367 switch (lifetime) {
368 case Qualifiers::OCL_None: llvm_unreachable("impossible");
369 case Qualifiers::OCL_ExplicitNone:
370 case Qualifiers::OCL_Autoreleasing:
371 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000372
John McCallf85e1932011-06-15 23:02:42 +0000373 case Qualifiers::OCL_Strong:
374 case Qualifiers::OCL_Weak:
375 info.NeedsCopyDispose = true;
376 }
377
378 // Block pointers require copy/dispose. So do Objective-C pointers.
379 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000380 info.NeedsCopyDispose = true;
381
382 // So do types that require non-trivial copy construction.
383 } else if (ci->hasCopyExpr()) {
384 info.NeedsCopyDispose = true;
385 info.HasCXXObject = true;
386
387 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000388 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000389 if (const CXXRecordDecl *record =
390 variable->getType()->getAsCXXRecordDecl()) {
391 if (!record->hasTrivialDestructor()) {
392 info.HasCXXObject = true;
393 info.NeedsCopyDispose = true;
394 }
395 }
396 }
397
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000398 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000399 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000400 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000401
John McCall6b5a61b2011-02-07 10:33:21 +0000402 maxFieldAlign = std::max(maxFieldAlign, align);
403
Jay Foadef6de3d2011-07-11 09:56:20 +0000404 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000405 CGM.getTypes().ConvertTypeForMem(VT);
406
John McCall6b5a61b2011-02-07 10:33:21 +0000407 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
408 }
409
410 // If that was everything, we're done here.
411 if (layout.empty()) {
412 info.StructureType =
413 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
414 info.CanBeGlobal = true;
415 return;
416 }
417
418 // Sort the layout by alignment. We have to use a stable sort here
419 // to get reproducible results. There should probably be an
420 // llvm::array_pod_stable_sort.
421 std::stable_sort(layout.begin(), layout.end());
422
423 CharUnits &blockSize = info.BlockSize;
424 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
425
426 // Assuming that the first byte in the header is maximally aligned,
427 // get the alignment of the first byte following the header.
428 CharUnits endAlign = getLowBit(blockSize);
429
430 // If the end of the header isn't satisfactorily aligned for the
431 // maximum thing, look for things that are okay with the header-end
432 // alignment, and keep appending them until we get something that's
433 // aligned right. This algorithm is only guaranteed optimal if
434 // that condition is satisfied at some point; otherwise we can get
435 // things like:
436 // header // next byte has alignment 4
437 // something_with_size_5; // next byte has alignment 1
438 // something_with_alignment_8;
439 // which has 7 bytes of padding, as opposed to the naive solution
440 // which might have less (?).
441 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000442 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000443 li = layout.begin() + 1, le = layout.end();
444
445 // Look for something that the header end is already
446 // satisfactorily aligned for.
447 for (; li != le && endAlign < li->Alignment; ++li)
448 ;
449
450 // If we found something that's naturally aligned for the end of
451 // the header, keep adding things...
452 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000453 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000454 for (; li != le; ++li) {
455 assert(endAlign >= li->Alignment);
456
457 li->setIndex(info, elementTypes.size());
458 elementTypes.push_back(li->Type);
459 blockSize += li->Size;
460 endAlign = getLowBit(blockSize);
461
462 // ...until we get to the alignment of the maximum field.
463 if (endAlign >= maxFieldAlign)
464 break;
465 }
466
467 // Don't re-append everything we just appended.
468 layout.erase(first, li);
469 }
470 }
471
John McCall6ea48412012-04-26 21:14:42 +0000472 assert(endAlign == getLowBit(blockSize));
473
John McCall6b5a61b2011-02-07 10:33:21 +0000474 // At this point, we just have to add padding if the end align still
475 // isn't aligned right.
476 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000477 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
478 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000479
John McCall5936e332011-02-15 09:22:45 +0000480 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
481 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000482 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000483 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000484 }
485
John McCall6c803f72012-05-01 20:28:00 +0000486 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000487 assert(endAlign == getLowBit(blockSize));
488
John McCall6b5a61b2011-02-07 10:33:21 +0000489 // Slam everything else on now. This works because they have
490 // strictly decreasing alignment and we expect that size is always a
491 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000492 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000493 li = layout.begin(), le = layout.end(); li != le; ++li) {
494 assert(endAlign >= li->Alignment);
495 li->setIndex(info, elementTypes.size());
496 elementTypes.push_back(li->Type);
497 blockSize += li->Size;
498 endAlign = getLowBit(blockSize);
499 }
500
501 info.StructureType =
502 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
503}
504
John McCall1a343eb2011-11-10 08:15:53 +0000505/// Enter the scope of a block. This should be run at the entrance to
506/// a full-expression so that the block's cleanups are pushed at the
507/// right place in the stack.
508static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000509 assert(CGF.HaveInsertPoint());
510
John McCall1a343eb2011-11-10 08:15:53 +0000511 // Allocate the block info and place it at the head of the list.
512 CGBlockInfo &blockInfo =
513 *new CGBlockInfo(block, CGF.CurFn->getName());
514 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
515 CGF.FirstBlockInfo = &blockInfo;
516
517 // Compute information about the layout, etc., of this block,
518 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000519 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000520
521 // Nothing else to do if it can be global.
522 if (blockInfo.CanBeGlobal) return;
523
524 // Make the allocation for the block.
525 blockInfo.Address =
526 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
527 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
528
529 // If there are cleanups to emit, enter them (but inactive).
530 if (!blockInfo.NeedsCopyDispose) return;
531
532 // Walk through the captures (in order) and find the ones not
533 // captured by constant.
534 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
535 ce = block->capture_end(); ci != ce; ++ci) {
536 // Ignore __block captures; there's nothing special in the
537 // on-stack block that we need to do for them.
538 if (ci->isByRef()) continue;
539
540 // Ignore variables that are constant-captured.
541 const VarDecl *variable = ci->getVariable();
542 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
543 if (capture.isConstant()) continue;
544
545 // Ignore objects that aren't destructed.
546 QualType::DestructionKind dtorKind =
547 variable->getType().isDestructedType();
548 if (dtorKind == QualType::DK_none) continue;
549
550 CodeGenFunction::Destroyer *destroyer;
551
552 // Block captures count as local values and have imprecise semantics.
553 // They also can't be arrays, so need to worry about that.
554 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000555 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000556 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000557 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000558 }
559
560 // GEP down to the address.
561 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
562 capture.getIndex());
563
John McCall6f103ba2011-11-10 10:43:54 +0000564 // We can use that GEP as the dominating IP.
565 if (!blockInfo.DominatingIP)
566 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
567
John McCall1a343eb2011-11-10 08:15:53 +0000568 CleanupKind cleanupKind = InactiveNormalCleanup;
569 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
570 if (useArrayEHCleanup)
571 cleanupKind = InactiveNormalAndEHCleanup;
572
573 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000574 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000575
576 // Remember where that cleanup was.
577 capture.setCleanup(CGF.EHStack.stable_begin());
578 }
579}
580
581/// Enter a full-expression with a non-trivial number of objects to
582/// clean up. This is in this file because, at the moment, the only
583/// kind of cleanup object is a BlockDecl*.
584void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
585 assert(E->getNumObjects() != 0);
586 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
587 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
588 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
589 enterBlockScope(*this, *i);
590 }
591}
592
593/// Find the layout for the given block in a linked list and remove it.
594static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
595 const BlockDecl *block) {
596 while (true) {
597 assert(head && *head);
598 CGBlockInfo *cur = *head;
599
600 // If this is the block we're looking for, splice it out of the list.
601 if (cur->getBlockDecl() == block) {
602 *head = cur->NextBlockInfo;
603 return cur;
604 }
605
606 head = &cur->NextBlockInfo;
607 }
608}
609
610/// Destroy a chain of block layouts.
611void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
612 assert(head && "destroying an empty chain");
613 do {
614 CGBlockInfo *cur = head;
615 head = cur->NextBlockInfo;
616 delete cur;
617 } while (head != 0);
618}
619
John McCall6b5a61b2011-02-07 10:33:21 +0000620/// Emit a block literal expression in the current function.
621llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000622 // If the block has no captures, we won't have a pre-computed
623 // layout for it.
624 if (!blockExpr->getBlockDecl()->hasCaptures()) {
625 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000626 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000627 blockInfo.BlockExpression = blockExpr;
628 return EmitBlockLiteral(blockInfo);
629 }
John McCall6b5a61b2011-02-07 10:33:21 +0000630
John McCall1a343eb2011-11-10 08:15:53 +0000631 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000632 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000633 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
634 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000635
John McCall1a343eb2011-11-10 08:15:53 +0000636 blockInfo->BlockExpression = blockExpr;
637 return EmitBlockLiteral(*blockInfo);
638}
639
640llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
641 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000642 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000643 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000644 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000645 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000646 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000647 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000648
649 // If there is nothing to capture, we can emit this as a global block.
650 if (blockInfo.CanBeGlobal)
651 return buildGlobalBlock(CGM, blockInfo, blockFn);
652
653 // Otherwise, we have to emit this as a local block.
654
655 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000656 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000657
658 // Build the block descriptor.
659 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
660
John McCall1a343eb2011-11-10 08:15:53 +0000661 llvm::AllocaInst *blockAddr = blockInfo.Address;
662 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000663
664 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000665 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000666 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
667 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000668 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000669
670 // Initialize the block literal.
671 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000672 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000673 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000674 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000675 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
676 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
677 "block.invoke"));
678 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
679 "block.descriptor"));
680
681 // Finally, capture all the values into the block.
682 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
683
684 // First, 'this'.
685 if (blockDecl->capturesCXXThis()) {
686 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
687 blockInfo.CXXThisIndex,
688 "block.captured-this.addr");
689 Builder.CreateStore(LoadCXXThis(), addr);
690 }
691
692 // Next, captured variables.
693 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
694 ce = blockDecl->capture_end(); ci != ce; ++ci) {
695 const VarDecl *variable = ci->getVariable();
696 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
697
698 // Ignore constant captures.
699 if (capture.isConstant()) continue;
700
701 QualType type = variable->getType();
702
703 // This will be a [[type]]*, except that a byref entry will just be
704 // an i8**.
705 llvm::Value *blockField =
706 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
707 "block.captured");
708
709 // Compute the address of the thing we're going to move into the
710 // block literal.
711 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000712 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000713 // We need to use the capture from the enclosing block.
714 const CGBlockInfo::Capture &enclosingCapture =
715 BlockInfo->getCapture(variable);
716
717 // This is a [[type]]*, except that a byref entry wil just be an i8**.
718 src = Builder.CreateStructGEP(LoadBlockStruct(),
719 enclosingCapture.getIndex(),
720 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000721 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000722 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000723 // special; we'll simply emit it directly.
724 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000725 } else {
726 // This is a [[type]]*.
727 src = LocalDeclMap[variable];
728 }
729
730 // For byrefs, we just write the pointer to the byref struct into
731 // the block field. There's no need to chase the forwarding
732 // pointer at this point, since we're building something that will
733 // live a shorter life than the stack byref anyway.
734 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000735 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000736 if (ci->isNested())
737 src = Builder.CreateLoad(src, "byref.capture");
738 else
John McCall5936e332011-02-15 09:22:45 +0000739 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000740
John McCall5936e332011-02-15 09:22:45 +0000741 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000742 Builder.CreateStore(src, blockField);
743
744 // If we have a copy constructor, evaluate that into the block field.
745 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000746 if (blockDecl->isConversionFromLambda()) {
747 // If we have a lambda conversion, emit the expression
748 // directly into the block instead.
749 CharUnits Align = getContext().getTypeAlignInChars(type);
750 AggValueSlot Slot =
751 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
752 AggValueSlot::IsDestructed,
753 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000754 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000755 EmitAggExpr(copyExpr, Slot);
756 } else {
757 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
758 }
John McCall6b5a61b2011-02-07 10:33:21 +0000759
760 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000761 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000762 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
763
764 // Otherwise, fake up a POD copy into the block field.
765 } else {
John McCallf85e1932011-06-15 23:02:42 +0000766 // Fake up a new variable so that EmitScalarInit doesn't think
767 // we're referring to the variable in its own initializer.
768 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000769 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000770
John McCallbb699b02011-02-07 18:37:40 +0000771 // We use one of these or the other depending on whether the
772 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000773 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
774 /*refersToEnclosing*/ ci->isNested(), type,
775 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000776
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000777 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000778 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000779 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000780 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000781 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000782 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000783 }
784
John McCall1a343eb2011-11-10 08:15:53 +0000785 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000786 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000787 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
788 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000789 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000790 }
John McCall6b5a61b2011-02-07 10:33:21 +0000791 }
792
793 // Cast to the converted block-pointer type, which happens (somewhat
794 // unfortunately) to be a pointer to function type.
795 llvm::Value *result =
796 Builder.CreateBitCast(blockAddr,
797 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000798
John McCall6b5a61b2011-02-07 10:33:21 +0000799 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000800}
801
802
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000803llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000804 if (BlockDescriptorType)
805 return BlockDescriptorType;
806
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000807 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000808 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000809
Mike Stumpab695142009-02-13 15:16:56 +0000810 // struct __block_descriptor {
811 // unsigned long reserved;
812 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000813 //
814 // // later, the following will be added
815 //
816 // struct {
817 // void (*copyHelper)();
818 // void (*copyHelper)();
819 // } helpers; // !!! optional
820 //
821 // const char *signature; // the block signature
822 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000823 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000824 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000825 llvm::StructType::create("struct.__block_descriptor",
826 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000827
John McCall6b5a61b2011-02-07 10:33:21 +0000828 // Now form a pointer to that.
829 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000830 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000831}
832
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000833llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000834 if (GenericBlockLiteralType)
835 return GenericBlockLiteralType;
836
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000837 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000838
Mike Stump9b8a7972009-02-13 15:25:34 +0000839 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000840 // void *__isa;
841 // int __flags;
842 // int __reserved;
843 // void (*__invoke)(void *);
844 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000845 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000846 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000847 llvm::StructType::create("struct.__block_literal_generic",
848 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
849 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000850
Mike Stump9b8a7972009-02-13 15:25:34 +0000851 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000852}
853
Mike Stumpbd65cac2009-02-19 01:01:04 +0000854
Anders Carlssona1736c02009-12-24 21:13:40 +0000855RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
856 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000857 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000858 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000859
Anders Carlssonacfde802009-02-12 00:39:25 +0000860 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
861
862 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000863 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000864 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000865
866 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000867 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000868 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
869
870 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000871 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000872
Benjamin Kramer578faa82011-09-27 21:06:10 +0000873 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000874
Anders Carlssonacfde802009-02-12 00:39:25 +0000875 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000876 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000877 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000878
Anders Carlsson782f3972009-04-08 23:13:16 +0000879 QualType FnType = BPT->getPointeeType();
880
Anders Carlssonacfde802009-02-12 00:39:25 +0000881 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000882 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000883 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000884
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000885 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000886 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000887
John McCall64cd2322011-03-09 08:39:33 +0000888 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000889 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000890 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000892 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000893 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner2acc6e32011-07-18 04:24:23 +0000895 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000896 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Anders Carlssonacfde802009-02-12 00:39:25 +0000898 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000899 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000900}
Anders Carlssond5cab542009-02-12 17:55:02 +0000901
John McCall6b5a61b2011-02-07 10:33:21 +0000902llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
903 bool isByRef) {
904 assert(BlockInfo && "evaluating block ref without block information?");
905 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000906
John McCall6b5a61b2011-02-07 10:33:21 +0000907 // Handle constant captures.
908 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000909
John McCall6b5a61b2011-02-07 10:33:21 +0000910 llvm::Value *addr =
911 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
912 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 if (isByRef) {
915 // addr should be a void** right now. Load, then cast the result
916 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000917
John McCall6b5a61b2011-02-07 10:33:21 +0000918 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000919 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000920 = llvm::PointerType::get(BuildByRefType(variable), 0);
921 addr = Builder.CreateBitCast(addr, byrefPointerType,
922 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000923
John McCall6b5a61b2011-02-07 10:33:21 +0000924 // Follow the forwarding pointer.
925 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
926 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000927
John McCall6b5a61b2011-02-07 10:33:21 +0000928 // Cast back to byref* and GEP over to the actual object.
929 addr = Builder.CreateBitCast(addr, byrefPointerType);
930 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
931 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000932 }
933
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000934 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000935 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000936
John McCall6b5a61b2011-02-07 10:33:21 +0000937 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000938}
939
Mike Stump67a64482009-02-14 22:16:35 +0000940llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000941CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000942 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000943 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
944 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000945
John McCall6b5a61b2011-02-07 10:33:21 +0000946 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000947 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000948
John McCall6b5a61b2011-02-07 10:33:21 +0000949 // Using that metadata, generate the actual block function.
950 llvm::Constant *blockFn;
951 {
952 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000953 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
954 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000955 0, LocalDeclMap,
956 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000957 }
John McCall5936e332011-02-15 09:22:45 +0000958 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000959
John McCalld16c2cf2011-02-08 08:22:06 +0000960 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000961}
962
John McCall6b5a61b2011-02-07 10:33:21 +0000963static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
964 const CGBlockInfo &blockInfo,
965 llvm::Constant *blockFn) {
966 assert(blockInfo.CanBeGlobal);
967
968 // Generate the constants for the block literal initializer.
969 llvm::Constant *fields[BlockHeaderSize];
970
971 // isa
972 fields[0] = CGM.getNSConcreteGlobalBlock();
973
974 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000975 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
976 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
977
John McCall5936e332011-02-15 09:22:45 +0000978 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000979
980 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000981 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000982
983 // Function
984 fields[3] = blockFn;
985
986 // Descriptor
987 fields[4] = buildBlockDescriptor(CGM, blockInfo);
988
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000989 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000990
991 llvm::GlobalVariable *literal =
992 new llvm::GlobalVariable(CGM.getModule(),
993 init->getType(),
994 /*constant*/ true,
995 llvm::GlobalVariable::InternalLinkage,
996 init,
997 "__block_literal_global");
998 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
999
1000 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001001 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001002 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1003 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001004}
1005
Mike Stump00470a12009-03-05 08:32:30 +00001006llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001007CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1008 const CGBlockInfo &blockInfo,
1009 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001010 const DeclMapTy &ldm,
1011 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001012 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001013
Devang Patel6d1155b2011-03-07 21:53:18 +00001014 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001015 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001016 CurGD = GD;
1017
John McCall6b5a61b2011-02-07 10:33:21 +00001018 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Mike Stump7f28a9c2009-03-13 23:34:28 +00001020 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001021 // to be local to this function as well, in case they're directly
1022 // referenced in a block.
1023 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1024 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1025 if (var && !var->hasLocalStorage())
1026 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001027 }
1028
John McCall6b5a61b2011-02-07 10:33:21 +00001029 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001030
John McCall6b5a61b2011-02-07 10:33:21 +00001031 // Build the argument list.
1032 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001033
John McCall6b5a61b2011-02-07 10:33:21 +00001034 // The first argument is the block pointer. Just take it as a void*
1035 // and cast it later.
1036 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001037 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001038
John McCall8178df32011-02-22 22:38:33 +00001039 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1040 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001041 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001042
John McCall6b5a61b2011-02-07 10:33:21 +00001043 // Now add the rest of the parameters.
1044 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1045 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001046 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001047
John McCall6b5a61b2011-02-07 10:33:21 +00001048 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001049 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001050 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001051 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1052 fnType->getExtInfo(),
1053 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001054 if (CGM.ReturnTypeUsesSRet(fnInfo))
1055 blockInfo.UsesStret = true;
1056
John McCallde5d3c72012-02-17 03:33:10 +00001057 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001058
John McCall6b5a61b2011-02-07 10:33:21 +00001059 MangleBuffer name;
1060 CGM.getBlockMangledName(GD, name, blockDecl);
1061 llvm::Function *fn =
1062 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1063 name.getString(), &CGM.getModule());
1064 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001065
John McCall6b5a61b2011-02-07 10:33:21 +00001066 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001067 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001068 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001069 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001070
John McCall8178df32011-02-22 22:38:33 +00001071 // Okay. Undo some of what StartFunction did.
1072
1073 // Pull the 'self' reference out of the local decl map.
1074 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1075 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001076 BlockPointer = Builder.CreateBitCast(blockAddr,
1077 blockInfo.StructureType->getPointerTo(),
1078 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001079
John McCallea1471e2010-05-20 01:18:31 +00001080 // If we have a C++ 'this' reference, go ahead and force it into
1081 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001082 if (blockDecl->capturesCXXThis()) {
1083 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1084 blockInfo.CXXThisIndex,
1085 "block.captured-this");
1086 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001087 }
1088
John McCall6b5a61b2011-02-07 10:33:21 +00001089 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1090 // appease it.
1091 if (const ObjCMethodDecl *method
1092 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1093 const VarDecl *self = method->getSelfDecl();
1094
1095 // There might not be a capture for 'self', but if there is...
1096 if (blockInfo.Captures.count(self)) {
1097 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1098 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1099 capture.getIndex(),
1100 "block.captured-self");
1101 LocalDeclMap[self] = selfAddr;
1102 }
1103 }
1104
1105 // Also force all the constant captures.
1106 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1107 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1108 const VarDecl *variable = ci->getVariable();
1109 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1110 if (!capture.isConstant()) continue;
1111
1112 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1113
1114 llvm::AllocaInst *alloca =
1115 CreateMemTemp(variable->getType(), "block.captured-const");
1116 alloca->setAlignment(align);
1117
1118 Builder.CreateStore(capture.getConstant(), alloca, align);
1119
1120 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001121 }
1122
John McCallf4b88a42012-03-10 09:33:50 +00001123 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001124 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1125 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1126 --entry_ptr;
1127
Eli Friedman64bee652012-02-25 02:48:22 +00001128 if (IsLambdaConversionToBlock)
1129 EmitLambdaBlockInvokeBody();
1130 else
1131 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001132
Mike Stumpde8c5c72009-10-01 00:27:30 +00001133 // Remember where we were...
1134 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001135
Mike Stumpde8c5c72009-10-01 00:27:30 +00001136 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001137 ++entry_ptr;
1138 Builder.SetInsertPoint(entry, entry_ptr);
1139
John McCallf4b88a42012-03-10 09:33:50 +00001140 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001141 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001142 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001143 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1144 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1145 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001146 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001147
Douglas Gregor4cdad312012-10-23 20:05:01 +00001148 if (CGM.getCodeGenOpts().getDebugInfo()
1149 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001150 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1151 if (capture.isConstant()) {
1152 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1153 Builder);
1154 continue;
1155 }
John McCall6b5a61b2011-02-07 10:33:21 +00001156
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001157 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1158 Builder, blockInfo);
1159 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001160 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001161 }
John McCall6b5a61b2011-02-07 10:33:21 +00001162
Mike Stumpde8c5c72009-10-01 00:27:30 +00001163 // And resume where we left off.
1164 if (resume == 0)
1165 Builder.ClearInsertionPoint();
1166 else
1167 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001168
John McCall6b5a61b2011-02-07 10:33:21 +00001169 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001170
John McCall6b5a61b2011-02-07 10:33:21 +00001171 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001172}
Mike Stumpa99038c2009-02-28 09:07:16 +00001173
John McCall6b5a61b2011-02-07 10:33:21 +00001174/*
1175 notes.push_back(HelperInfo());
1176 HelperInfo &note = notes.back();
1177 note.index = capture.getIndex();
1178 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1179 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001180
John McCall6b5a61b2011-02-07 10:33:21 +00001181 if (ci->isByRef()) {
1182 note.flag = BLOCK_FIELD_IS_BYREF;
1183 if (type.isObjCGCWeak())
1184 note.flag |= BLOCK_FIELD_IS_WEAK;
1185 } else if (type->isBlockPointerType()) {
1186 note.flag = BLOCK_FIELD_IS_BLOCK;
1187 } else {
1188 note.flag = BLOCK_FIELD_IS_OBJECT;
1189 }
1190 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001191
Mike Stump00470a12009-03-05 08:32:30 +00001192
Mike Stumpa99038c2009-02-28 09:07:16 +00001193
John McCall6b5a61b2011-02-07 10:33:21 +00001194llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001195CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001196 ASTContext &C = getContext();
1197
1198 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001199 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1200 args.push_back(&dstDecl);
1201 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1202 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Mike Stumpa4f668f2009-03-06 01:33:24 +00001204 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001205 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1206 FunctionType::ExtInfo(),
1207 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001208
John McCall6b5a61b2011-02-07 10:33:21 +00001209 // FIXME: it would be nice if these were mergeable with things with
1210 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001211 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001212
1213 llvm::Function *Fn =
1214 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001215 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001216
1217 IdentifierInfo *II
1218 = &CGM.getContext().Idents.get("__copy_helper_block_");
1219
Devang Patel58dc5ca2011-05-02 20:37:08 +00001220 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001221 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001222
John McCall6b5a61b2011-02-07 10:33:21 +00001223 FunctionDecl *FD = FunctionDecl::Create(C,
1224 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001225 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001226 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001227 SC_Static,
1228 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001229 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001230 false);
John McCalld26bc762011-03-09 04:27:21 +00001231 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001232
Chris Lattner2acc6e32011-07-18 04:24:23 +00001233 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001234
John McCalld26bc762011-03-09 04:27:21 +00001235 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001236 src = Builder.CreateLoad(src);
1237 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001238
John McCalld26bc762011-03-09 04:27:21 +00001239 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001240 dst = Builder.CreateLoad(dst);
1241 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001242
John McCall6b5a61b2011-02-07 10:33:21 +00001243 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001244
John McCall6b5a61b2011-02-07 10:33:21 +00001245 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1246 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1247 const VarDecl *variable = ci->getVariable();
1248 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001249
John McCall6b5a61b2011-02-07 10:33:21 +00001250 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1251 if (capture.isConstant()) continue;
1252
1253 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001254 BlockFieldFlags flags;
1255
John McCall015f33b2012-10-17 02:28:37 +00001256 bool useARCWeakCopy = false;
1257 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001258
1259 if (copyExpr) {
1260 assert(!ci->isByRef());
1261 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001262
John McCall6b5a61b2011-02-07 10:33:21 +00001263 } else if (ci->isByRef()) {
1264 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001265 if (type.isObjCGCWeak())
1266 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001267
John McCallf85e1932011-06-15 23:02:42 +00001268 } else if (type->isObjCRetainableType()) {
1269 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001270 bool isBlockPointer = type->isBlockPointerType();
1271 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001272 flags = BLOCK_FIELD_IS_BLOCK;
1273
1274 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001275 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001276 Qualifiers qs = type.getQualifiers();
1277
John McCall015f33b2012-10-17 02:28:37 +00001278 // We need to register __weak direct captures with the runtime.
1279 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1280 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001281
John McCall015f33b2012-10-17 02:28:37 +00001282 // We need to retain the copied value for __strong direct captures.
1283 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1284 // If it's a block pointer, we have to copy the block and
1285 // assign that to the destination pointer, so we might as
1286 // well use _Block_object_assign. Otherwise we can avoid that.
1287 if (!isBlockPointer)
1288 useARCStrongCopy = true;
1289
1290 // Otherwise the memcpy is fine.
1291 } else {
1292 continue;
1293 }
1294
1295 // Non-ARC captures of retainable pointers are strong and
1296 // therefore require a call to _Block_object_assign.
1297 } else {
1298 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001299 }
1300 } else {
1301 continue;
1302 }
John McCall6b5a61b2011-02-07 10:33:21 +00001303
1304 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001305 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1306 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001307
1308 // If there's an explicit copy expression, we do that.
1309 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001310 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001311 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001312 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001313 } else {
1314 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001315 if (useARCStrongCopy) {
1316 // At -O0, store null into the destination field (so that the
1317 // storeStrong doesn't over-release) and then call storeStrong.
1318 // This is a workaround to not having an initStrong call.
1319 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1320 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1321 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1322 Builder.CreateStore(null, dstField);
1323 EmitARCStoreStrongCall(dstField, srcValue, true);
1324
1325 // With optimization enabled, take advantage of the fact that
1326 // the blocks runtime guarantees a memcpy of the block data, and
1327 // just emit a retain of the src field.
1328 } else {
1329 EmitARCRetainNonBlock(srcValue);
1330
1331 // We don't need this anymore, so kill it. It's not quite
1332 // worth the annoyance to avoid creating it in the first place.
1333 cast<llvm::Instruction>(dstField)->eraseFromParent();
1334 }
1335 } else {
1336 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1337 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1338 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1339 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1340 }
Mike Stump08920992009-03-07 02:35:30 +00001341 }
1342 }
1343
John McCalld16c2cf2011-02-08 08:22:06 +00001344 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001345
John McCall5936e332011-02-15 09:22:45 +00001346 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001347}
1348
John McCall6b5a61b2011-02-07 10:33:21 +00001349llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001350CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001351 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001352
John McCall6b5a61b2011-02-07 10:33:21 +00001353 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001354 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1355 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Mike Stumpa4f668f2009-03-06 01:33:24 +00001357 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001358 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1359 FunctionType::ExtInfo(),
1360 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001361
Mike Stump3899a7f2009-06-05 23:26:36 +00001362 // FIXME: We'd like to put these into a mergable by content, with
1363 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001364 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001365
1366 llvm::Function *Fn =
1367 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001368 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001369
Devang Patel58dc5ca2011-05-02 20:37:08 +00001370 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001371 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001372
Mike Stumpa4f668f2009-03-06 01:33:24 +00001373 IdentifierInfo *II
1374 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1375
John McCall6b5a61b2011-02-07 10:33:21 +00001376 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001377 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001378 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001379 SC_Static,
1380 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001381 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001382 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001383
Chris Lattner2acc6e32011-07-18 04:24:23 +00001384 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001385
John McCalld26bc762011-03-09 04:27:21 +00001386 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001387 src = Builder.CreateLoad(src);
1388 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001389
John McCall6b5a61b2011-02-07 10:33:21 +00001390 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1391
John McCalld16c2cf2011-02-08 08:22:06 +00001392 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001393
1394 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1395 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1396 const VarDecl *variable = ci->getVariable();
1397 QualType type = variable->getType();
1398
1399 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1400 if (capture.isConstant()) continue;
1401
John McCalld16c2cf2011-02-08 08:22:06 +00001402 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001403 const CXXDestructorDecl *dtor = 0;
1404
John McCall015f33b2012-10-17 02:28:37 +00001405 bool useARCWeakDestroy = false;
1406 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001407
John McCall6b5a61b2011-02-07 10:33:21 +00001408 if (ci->isByRef()) {
1409 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001410 if (type.isObjCGCWeak())
1411 flags |= BLOCK_FIELD_IS_WEAK;
1412 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1413 if (record->hasTrivialDestructor())
1414 continue;
1415 dtor = record->getDestructor();
1416 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001417 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001418 if (type->isBlockPointerType())
1419 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001420
John McCallf85e1932011-06-15 23:02:42 +00001421 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001422 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001423 Qualifiers qs = type.getQualifiers();
1424
1425 // Don't generate special dispose logic for a captured object
1426 // unless it's __strong or __weak.
1427 if (!qs.hasStrongOrWeakObjCLifetime())
1428 continue;
1429
1430 // Support __weak direct captures.
1431 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001432 useARCWeakDestroy = true;
1433
1434 // Tools really want us to use objc_storeStrong here.
1435 else
1436 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001437 }
1438 } else {
1439 continue;
1440 }
John McCall6b5a61b2011-02-07 10:33:21 +00001441
1442 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001443 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001444
1445 // If there's an explicit copy expression, we do that.
1446 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001447 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001448
John McCallf85e1932011-06-15 23:02:42 +00001449 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001450 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001451 EmitARCDestroyWeak(srcField);
1452
John McCall015f33b2012-10-17 02:28:37 +00001453 // Destroy strong objects with a call if requested.
1454 } else if (useARCStrongDestroy) {
1455 EmitARCDestroyStrong(srcField, /*precise*/ false);
1456
John McCall6b5a61b2011-02-07 10:33:21 +00001457 // Otherwise we call _Block_object_dispose. It wouldn't be too
1458 // hard to just emit this as a cleanup if we wanted to make sure
1459 // that things were done in reverse.
1460 } else {
1461 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001462 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001463 BuildBlockRelease(value, flags);
1464 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001465 }
1466
John McCall6b5a61b2011-02-07 10:33:21 +00001467 cleanups.ForceCleanup();
1468
John McCalld16c2cf2011-02-08 08:22:06 +00001469 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001470
John McCall5936e332011-02-15 09:22:45 +00001471 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001472}
1473
John McCallf0c11f72011-03-31 08:03:29 +00001474namespace {
1475
1476/// Emits the copy/dispose helper functions for a __block object of id type.
1477class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1478 BlockFieldFlags Flags;
1479
1480public:
1481 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1482 : ByrefHelpers(alignment), Flags(flags) {}
1483
John McCall36170192011-03-31 09:19:20 +00001484 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1485 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001486 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1487
1488 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1489 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1490
1491 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1492
1493 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1494 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1495 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1496 }
1497
1498 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1499 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1500 llvm::Value *value = CGF.Builder.CreateLoad(field);
1501
1502 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1503 }
1504
1505 void profileImpl(llvm::FoldingSetNodeID &id) const {
1506 id.AddInteger(Flags.getBitMask());
1507 }
1508};
1509
John McCallf85e1932011-06-15 23:02:42 +00001510/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1511class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1512public:
1513 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1514
1515 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1516 llvm::Value *srcField) {
1517 CGF.EmitARCMoveWeak(destField, srcField);
1518 }
1519
1520 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1521 CGF.EmitARCDestroyWeak(field);
1522 }
1523
1524 void profileImpl(llvm::FoldingSetNodeID &id) const {
1525 // 0 is distinguishable from all pointers and byref flags
1526 id.AddInteger(0);
1527 }
1528};
1529
1530/// Emits the copy/dispose helpers for an ARC __block __strong variable
1531/// that's not of block-pointer type.
1532class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1533public:
1534 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1535
1536 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1537 llvm::Value *srcField) {
1538 // Do a "move" by copying the value and then zeroing out the old
1539 // variable.
1540
John McCalla59e4b72011-11-09 03:17:26 +00001541 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1542 value->setAlignment(Alignment.getQuantity());
1543
John McCallf85e1932011-06-15 23:02:42 +00001544 llvm::Value *null =
1545 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001546
1547 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1548 store->setAlignment(Alignment.getQuantity());
1549
1550 store = CGF.Builder.CreateStore(null, srcField);
1551 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001552 }
1553
1554 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001555 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001556 }
1557
1558 void profileImpl(llvm::FoldingSetNodeID &id) const {
1559 // 1 is distinguishable from all pointers and byref flags
1560 id.AddInteger(1);
1561 }
1562};
1563
John McCalla59e4b72011-11-09 03:17:26 +00001564/// Emits the copy/dispose helpers for an ARC __block __strong
1565/// variable that's of block-pointer type.
1566class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1567public:
1568 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1569
1570 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1571 llvm::Value *srcField) {
1572 // Do the copy with objc_retainBlock; that's all that
1573 // _Block_object_assign would do anyway, and we'd have to pass the
1574 // right arguments to make sure it doesn't get no-op'ed.
1575 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1576 oldValue->setAlignment(Alignment.getQuantity());
1577
1578 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1579
1580 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1581 store->setAlignment(Alignment.getQuantity());
1582 }
1583
1584 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001585 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001586 }
1587
1588 void profileImpl(llvm::FoldingSetNodeID &id) const {
1589 // 2 is distinguishable from all pointers and byref flags
1590 id.AddInteger(2);
1591 }
1592};
1593
John McCallf0c11f72011-03-31 08:03:29 +00001594/// Emits the copy/dispose helpers for a __block variable with a
1595/// nontrivial copy constructor or destructor.
1596class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1597 QualType VarType;
1598 const Expr *CopyExpr;
1599
1600public:
1601 CXXByrefHelpers(CharUnits alignment, QualType type,
1602 const Expr *copyExpr)
1603 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1604
1605 bool needsCopy() const { return CopyExpr != 0; }
1606 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1607 llvm::Value *srcField) {
1608 if (!CopyExpr) return;
1609 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1610 }
1611
1612 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1613 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1614 CGF.PushDestructorCleanup(VarType, field);
1615 CGF.PopCleanupBlocks(cleanupDepth);
1616 }
1617
1618 void profileImpl(llvm::FoldingSetNodeID &id) const {
1619 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1620 }
1621};
1622} // end anonymous namespace
1623
1624static llvm::Constant *
1625generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001626 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001627 CodeGenModule::ByrefHelpers &byrefInfo) {
1628 ASTContext &Context = CGF.getContext();
1629
1630 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001631
John McCalld26bc762011-03-09 04:27:21 +00001632 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001633 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001634 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001635
John McCallf0c11f72011-03-31 08:03:29 +00001636 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001637 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Mike Stump45031c02009-03-06 02:29:21 +00001639 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001640 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1641 FunctionType::ExtInfo(),
1642 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001643
John McCallf0c11f72011-03-31 08:03:29 +00001644 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001645 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001646
Mike Stump3899a7f2009-06-05 23:26:36 +00001647 // FIXME: We'd like to put these into a mergable by content, with
1648 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001649 llvm::Function *Fn =
1650 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001651 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001652
1653 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001654 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001655
John McCallf0c11f72011-03-31 08:03:29 +00001656 FunctionDecl *FD = FunctionDecl::Create(Context,
1657 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001658 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001659 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001660 SC_Static,
1661 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001662 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001663
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001664 // Initialize debug info if necessary.
1665 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001666 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001667
John McCallf0c11f72011-03-31 08:03:29 +00001668 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001669 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001670
John McCallf0c11f72011-03-31 08:03:29 +00001671 // dst->x
1672 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1673 destField = CGF.Builder.CreateLoad(destField);
1674 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1675 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001676
John McCallf0c11f72011-03-31 08:03:29 +00001677 // src->x
1678 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1679 srcField = CGF.Builder.CreateLoad(srcField);
1680 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1681 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1682
1683 byrefInfo.emitCopy(CGF, destField, srcField);
1684 }
1685
1686 CGF.FinishFunction();
1687
1688 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001689}
1690
John McCallf0c11f72011-03-31 08:03:29 +00001691/// Build the copy helper for a __block variable.
1692static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001693 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001694 CodeGenModule::ByrefHelpers &info) {
1695 CodeGenFunction CGF(CGM);
1696 return generateByrefCopyHelper(CGF, byrefType, info);
1697}
1698
1699/// Generate code for a __block variable's dispose helper.
1700static llvm::Constant *
1701generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001702 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001703 CodeGenModule::ByrefHelpers &byrefInfo) {
1704 ASTContext &Context = CGF.getContext();
1705 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001706
John McCalld26bc762011-03-09 04:27:21 +00001707 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001708 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001709 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Mike Stump45031c02009-03-06 02:29:21 +00001711 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001712 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1713 FunctionType::ExtInfo(),
1714 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001715
John McCallf0c11f72011-03-31 08:03:29 +00001716 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001717 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001718
Mike Stump3899a7f2009-06-05 23:26:36 +00001719 // FIXME: We'd like to put these into a mergable by content, with
1720 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001721 llvm::Function *Fn =
1722 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001723 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001724 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001725
1726 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001727 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001728
John McCallf0c11f72011-03-31 08:03:29 +00001729 FunctionDecl *FD = FunctionDecl::Create(Context,
1730 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001731 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001732 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001733 SC_Static,
1734 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001735 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001736 // Initialize debug info if necessary.
1737 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001738 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001739
John McCallf0c11f72011-03-31 08:03:29 +00001740 if (byrefInfo.needsDispose()) {
1741 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1742 V = CGF.Builder.CreateLoad(V);
1743 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1744 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001745
John McCallf0c11f72011-03-31 08:03:29 +00001746 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001747 }
Mike Stump45031c02009-03-06 02:29:21 +00001748
John McCallf0c11f72011-03-31 08:03:29 +00001749 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001750
John McCallf0c11f72011-03-31 08:03:29 +00001751 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001752}
1753
John McCallf0c11f72011-03-31 08:03:29 +00001754/// Build the dispose helper for a __block variable.
1755static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001756 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001757 CodeGenModule::ByrefHelpers &info) {
1758 CodeGenFunction CGF(CGM);
1759 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001760}
1761
John McCallf0c11f72011-03-31 08:03:29 +00001762///
1763template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001764 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001765 T &byrefInfo) {
1766 // Increase the field's alignment to be at least pointer alignment,
1767 // since the layout of the byref struct will guarantee at least that.
1768 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1769 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1770
1771 llvm::FoldingSetNodeID id;
1772 byrefInfo.Profile(id);
1773
1774 void *insertPos;
1775 CodeGenModule::ByrefHelpers *node
1776 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1777 if (node) return static_cast<T*>(node);
1778
1779 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1780 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1781
1782 T *copy = new (CGM.getContext()) T(byrefInfo);
1783 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1784 return copy;
1785}
1786
1787CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001788CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001789 const AutoVarEmission &emission) {
1790 const VarDecl &var = *emission.Variable;
1791 QualType type = var.getType();
1792
1793 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1794 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1795 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1796
1797 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1798 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1799 }
1800
John McCallf85e1932011-06-15 23:02:42 +00001801 // Otherwise, if we don't have a retainable type, there's nothing to do.
1802 // that the runtime does extra copies.
1803 if (!type->isObjCRetainableType()) return 0;
1804
1805 Qualifiers qs = type.getQualifiers();
1806
1807 // If we have lifetime, that dominates.
1808 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001809 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001810
1811 switch (lifetime) {
1812 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1813
1814 // These are just bits as far as the runtime is concerned.
1815 case Qualifiers::OCL_ExplicitNone:
1816 case Qualifiers::OCL_Autoreleasing:
1817 return 0;
1818
1819 // Tell the runtime that this is ARC __weak, called by the
1820 // byref routines.
1821 case Qualifiers::OCL_Weak: {
1822 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1823 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1824 }
1825
1826 // ARC __strong __block variables need to be retained.
1827 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001828 // Block pointers need to be copied, and there's no direct
1829 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001830 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001831 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001832 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1833
1834 // Otherwise, we transfer ownership of the retain from the stack
1835 // to the heap.
1836 } else {
1837 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1838 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1839 }
1840 }
1841 llvm_unreachable("fell out of lifetime switch!");
1842 }
1843
John McCallf0c11f72011-03-31 08:03:29 +00001844 BlockFieldFlags flags;
1845 if (type->isBlockPointerType()) {
1846 flags |= BLOCK_FIELD_IS_BLOCK;
1847 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1848 type->isObjCObjectPointerType()) {
1849 flags |= BLOCK_FIELD_IS_OBJECT;
1850 } else {
1851 return 0;
1852 }
1853
1854 if (type.isObjCGCWeak())
1855 flags |= BLOCK_FIELD_IS_WEAK;
1856
1857 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1858 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001859}
1860
John McCall5af02db2011-03-31 01:59:53 +00001861unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1862 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1863
1864 return ByRefValueInfo.find(VD)->second.second;
1865}
1866
1867llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1868 const VarDecl *V) {
1869 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1870 Loc = Builder.CreateLoad(Loc);
1871 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1872 V->getNameAsString());
1873 return Loc;
1874}
1875
1876/// BuildByRefType - This routine changes a __block variable declared as T x
1877/// into:
1878///
1879/// struct {
1880/// void *__isa;
1881/// void *__forwarding;
1882/// int32_t __flags;
1883/// int32_t __size;
1884/// void *__copy_helper; // only if needed
1885/// void *__destroy_helper; // only if needed
1886/// char padding[X]; // only if needed
1887/// T x;
1888/// } x
1889///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001890llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1891 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001892 if (Info.first)
1893 return Info.first;
1894
1895 QualType Ty = D->getType();
1896
Chris Lattner5f9e2722011-07-23 10:55:15 +00001897 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001898
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001899 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001900 llvm::StructType::create(getLLVMContext(),
1901 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001902
1903 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001904 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001905
1906 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001907 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001908
1909 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001910 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001911
1912 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001913 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001914
David Chisnall9595dae2012-04-04 13:07:13 +00001915 bool HasCopyAndDispose =
1916 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001917 if (HasCopyAndDispose) {
1918 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001919 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001920
1921 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001922 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001923 }
1924
1925 bool Packed = false;
1926 CharUnits Align = getContext().getDeclAlign(D);
1927 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1928 // We have to insert padding.
1929
1930 // The struct above has 2 32-bit integers.
1931 unsigned CurrentOffsetInBytes = 4 * 2;
1932
1933 // And either 2 or 4 pointers.
1934 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
Micah Villmow25a6a842012-10-08 16:25:52 +00001935 CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001936
1937 // Align the offset.
1938 unsigned AlignedOffsetInBytes =
1939 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1940
1941 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1942 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001943 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001944 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001945 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001946 if (NumPaddingBytes > 1)
1947 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1948
John McCall0774cb82011-05-15 01:53:33 +00001949 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001950
1951 // We want a packed struct.
1952 Packed = true;
1953 }
1954 }
1955
1956 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001957 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001958
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001959 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001960
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001961 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001962
John McCall0774cb82011-05-15 01:53:33 +00001963 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001964
1965 return Info.first;
1966}
1967
1968/// Initialize the structural components of a __block variable, i.e.
1969/// everything but the actual object.
1970void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001971 // Find the address of the local.
1972 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001973
John McCallf0c11f72011-03-31 08:03:29 +00001974 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001975 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001976 cast<llvm::PointerType>(addr->getType())->getElementType());
1977
1978 // Build the byref helpers if necessary. This is null if we don't need any.
1979 CodeGenModule::ByrefHelpers *helpers =
1980 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001981
1982 const VarDecl &D = *emission.Variable;
1983 QualType type = D.getType();
1984
John McCallf0c11f72011-03-31 08:03:29 +00001985 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001986
1987 // Initialize the 'isa', which is just 0 or 1.
1988 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001989 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001990 isa = 1;
1991 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1992 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1993
1994 // Store the address of the variable into its own forwarding pointer.
1995 Builder.CreateStore(addr,
1996 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
1997
1998 // Blocks ABI:
1999 // c) the flags field is set to either 0 if no helper functions are
2000 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
2001 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00002002 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00002003 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2004 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2005
John McCallf0c11f72011-03-31 08:03:29 +00002006 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2007 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002008 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2009
John McCallf0c11f72011-03-31 08:03:29 +00002010 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002011 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002012 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002013
2014 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002015 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002016 }
2017}
2018
John McCalld16c2cf2011-02-08 08:22:06 +00002019void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002020 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002021 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002022 V = Builder.CreateBitCast(V, Int8PtrTy);
2023 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002024 Builder.CreateCall2(F, V, N);
2025}
John McCall5af02db2011-03-31 01:59:53 +00002026
2027namespace {
2028 struct CallBlockRelease : EHScopeStack::Cleanup {
2029 llvm::Value *Addr;
2030 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2031
John McCallad346f42011-07-12 20:27:29 +00002032 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002033 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002034 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2035 }
2036 };
2037}
2038
2039/// Enter a cleanup to destroy a __block variable. Note that this
2040/// cleanup should be a no-op if the variable hasn't left the stack
2041/// yet; if a cleanup is required for the variable itself, that needs
2042/// to be done externally.
2043void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2044 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002045 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002046 return;
2047
2048 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2049}
John McCall13db5cf2011-09-09 20:41:01 +00002050
2051/// Adjust the declaration of something from the blocks API.
2052static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2053 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002054 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002055
2056 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2057 if (GV->isDeclaration() &&
2058 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2059 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2060}
2061
2062llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2063 if (BlockObjectDispose)
2064 return BlockObjectDispose;
2065
2066 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2067 llvm::FunctionType *fty
2068 = llvm::FunctionType::get(VoidTy, args, false);
2069 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2070 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2071 return BlockObjectDispose;
2072}
2073
2074llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2075 if (BlockObjectAssign)
2076 return BlockObjectAssign;
2077
2078 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2079 llvm::FunctionType *fty
2080 = llvm::FunctionType::get(VoidTy, args, false);
2081 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2082 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2083 return BlockObjectAssign;
2084}
2085
2086llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2087 if (NSConcreteGlobalBlock)
2088 return NSConcreteGlobalBlock;
2089
2090 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2091 Int8PtrTy->getPointerTo(), 0);
2092 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2093 return NSConcreteGlobalBlock;
2094}
2095
2096llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2097 if (NSConcreteStackBlock)
2098 return NSConcreteStackBlock;
2099
2100 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2101 Int8PtrTy->getPointerTo(), 0);
2102 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2103 return NSConcreteStackBlock;
2104}