blob: 00203bebf619692e3d223188112b8e957c7e5065 [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.
Fariborz Jahanianc46b4352012-10-27 21:10:38 +0000106 if (C.getLangOpts().ObjC1) {
107 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
108 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
109 else
110 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
111 }
John McCall6b5a61b2011-02-07 10:33:21 +0000112 else
113 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garst2a7eb282010-02-23 21:51:17 +0000114
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000115 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stumpe5fee252009-02-13 16:19:19 +0000116
John McCall6b5a61b2011-02-07 10:33:21 +0000117 llvm::GlobalVariable *global =
118 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
119 llvm::GlobalValue::InternalLinkage,
120 init, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000121
John McCall6b5a61b2011-02-07 10:33:21 +0000122 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000123}
124
John McCall6b5a61b2011-02-07 10:33:21 +0000125/*
126 Purely notional variadic template describing the layout of a block.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000127
John McCall6b5a61b2011-02-07 10:33:21 +0000128 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
129 struct Block_literal {
130 /// Initialized to one of:
131 /// extern void *_NSConcreteStackBlock[];
132 /// extern void *_NSConcreteGlobalBlock[];
133 ///
134 /// In theory, we could start one off malloc'ed by setting
135 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
136 /// this isa:
137 /// extern void *_NSConcreteMallocBlock[];
138 struct objc_class *isa;
Mike Stump00470a12009-03-05 08:32:30 +0000139
John McCall6b5a61b2011-02-07 10:33:21 +0000140 /// These are the flags (with corresponding bit number) that the
141 /// compiler is actually supposed to know about.
142 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
143 /// descriptor provides copy and dispose helper functions
144 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
145 /// object with a nontrivial destructor or copy constructor
146 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
147 /// as global memory
148 /// 29. BLOCK_USE_STRET - indicates that the block function
149 /// uses stret, which objc_msgSend needs to know about
150 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
151 /// @encoded signature string
152 /// And we're not supposed to manipulate these:
153 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
154 /// to malloc'ed memory
155 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
156 /// to GC-allocated memory
157 /// Additionally, the bottom 16 bits are a reference count which
158 /// should be zero on the stack.
159 int flags;
David Chisnall5e530af2009-11-17 19:33:30 +0000160
John McCall6b5a61b2011-02-07 10:33:21 +0000161 /// Reserved; should be zero-initialized.
162 int reserved;
David Chisnall5e530af2009-11-17 19:33:30 +0000163
John McCall6b5a61b2011-02-07 10:33:21 +0000164 /// Function pointer generated from block literal.
165 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stumpe5fee252009-02-13 16:19:19 +0000166
John McCall6b5a61b2011-02-07 10:33:21 +0000167 /// Block description metadata generated from block literal.
168 struct Block_descriptor *block_descriptor;
John McCall711c52b2011-01-05 12:14:39 +0000169
John McCall6b5a61b2011-02-07 10:33:21 +0000170 /// Captured values follow.
171 _CapturesTypes captures...;
172 };
173 */
David Chisnall5e530af2009-11-17 19:33:30 +0000174
John McCall6b5a61b2011-02-07 10:33:21 +0000175/// The number of fields in a block header.
176const unsigned BlockHeaderSize = 5;
Mike Stump00470a12009-03-05 08:32:30 +0000177
John McCall6b5a61b2011-02-07 10:33:21 +0000178namespace {
179 /// A chunk of data that we actually have to capture in the block.
180 struct BlockLayoutChunk {
181 CharUnits Alignment;
182 CharUnits Size;
183 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foadef6de3d2011-07-11 09:56:20 +0000184 llvm::Type *Type;
Mike Stumpe5fee252009-02-13 16:19:19 +0000185
John McCall6b5a61b2011-02-07 10:33:21 +0000186 BlockLayoutChunk(CharUnits align, CharUnits size,
187 const BlockDecl::Capture *capture,
Jay Foadef6de3d2011-07-11 09:56:20 +0000188 llvm::Type *type)
John McCall6b5a61b2011-02-07 10:33:21 +0000189 : Alignment(align), Size(size), Capture(capture), Type(type) {}
Mike Stumpe5fee252009-02-13 16:19:19 +0000190
John McCall6b5a61b2011-02-07 10:33:21 +0000191 /// Tell the block info that this chunk has the given field index.
192 void setIndex(CGBlockInfo &info, unsigned index) {
193 if (!Capture)
194 info.CXXThisIndex = index;
John McCallea1471e2010-05-20 01:18:31 +0000195 else
John McCall6b5a61b2011-02-07 10:33:21 +0000196 info.Captures[Capture->getVariable()]
197 = CGBlockInfo::Capture::makeIndex(index);
John McCallea1471e2010-05-20 01:18:31 +0000198 }
John McCall6b5a61b2011-02-07 10:33:21 +0000199 };
Mike Stumpcf62d392009-03-06 18:42:23 +0000200
John McCall6b5a61b2011-02-07 10:33:21 +0000201 /// Order by descending alignment.
202 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
203 return left.Alignment > right.Alignment;
204 }
205}
206
John McCall461c9c12011-02-08 03:07:00 +0000207/// Determines if the given type is safe for constant capture in C++.
208static bool isSafeForCXXConstantCapture(QualType type) {
209 const RecordType *recordType =
210 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
211
212 // Only records can be unsafe.
213 if (!recordType) return true;
214
215 const CXXRecordDecl *record = cast<CXXRecordDecl>(recordType->getDecl());
216
217 // Maintain semantics for classes with non-trivial dtors or copy ctors.
218 if (!record->hasTrivialDestructor()) return false;
219 if (!record->hasTrivialCopyConstructor()) return false;
220
221 // Otherwise, we just have to make sure there aren't any mutable
222 // fields that might have changed since initialization.
Douglas Gregor2bb11012011-05-13 01:05:07 +0000223 return !record->hasMutableFields();
John McCall461c9c12011-02-08 03:07:00 +0000224}
225
John McCall6b5a61b2011-02-07 10:33:21 +0000226/// It is illegal to modify a const object after initialization.
227/// Therefore, if a const object has a constant initializer, we don't
228/// actually need to keep storage for it in the block; we'll just
229/// rematerialize it at the start of the block function. This is
230/// acceptable because we make no promises about address stability of
231/// captured variables.
232static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smith2d6a5672012-01-14 04:30:29 +0000233 CodeGenFunction *CGF,
John McCall6b5a61b2011-02-07 10:33:21 +0000234 const VarDecl *var) {
235 QualType type = var->getType();
236
237 // We can only do this if the variable is const.
238 if (!type.isConstQualified()) return 0;
239
John McCall461c9c12011-02-08 03:07:00 +0000240 // Furthermore, in C++ we have to worry about mutable fields:
241 // C++ [dcl.type.cv]p4:
242 // Except that any class member declared mutable can be
243 // modified, any attempt to modify a const object during its
244 // lifetime results in undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +0000245 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
John McCall6b5a61b2011-02-07 10:33:21 +0000246 return 0;
247
248 // If the variable doesn't have any initializer (shouldn't this be
249 // invalid?), it's not clear what we should do. Maybe capture as
250 // zero?
251 const Expr *init = var->getInit();
252 if (!init) return 0;
253
Richard Smith2d6a5672012-01-14 04:30:29 +0000254 return CGM.EmitConstantInit(*var, CGF);
John McCall6b5a61b2011-02-07 10:33:21 +0000255}
256
257/// Get the low bit of a nonzero character count. This is the
258/// alignment of the nth byte if the 0th byte is universally aligned.
259static CharUnits getLowBit(CharUnits v) {
260 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
261}
262
263static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000264 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall6b5a61b2011-02-07 10:33:21 +0000265 ASTContext &C = CGM.getContext();
266
267 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
268 CharUnits ptrSize, ptrAlign, intSize, intAlign;
269 llvm::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
270 llvm::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
271
272 // Are there crazy embedded platforms where this isn't true?
273 assert(intSize <= ptrSize && "layout assumptions horribly violated");
274
275 CharUnits headerSize = ptrSize;
276 if (2 * intSize < ptrAlign) headerSize += ptrSize;
277 else headerSize += 2 * intSize;
278 headerSize += 2 * ptrSize;
279
280 info.BlockAlign = ptrAlign;
281 info.BlockSize = headerSize;
282
283 assert(elementTypes.empty());
Jay Foadef6de3d2011-07-11 09:56:20 +0000284 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
285 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000286 elementTypes.push_back(i8p);
287 elementTypes.push_back(intTy);
288 elementTypes.push_back(intTy);
289 elementTypes.push_back(i8p);
290 elementTypes.push_back(CGM.getBlockDescriptorType());
291
292 assert(elementTypes.size() == BlockHeaderSize);
293}
294
295/// Compute the layout of the given block. Attempts to lay the block
296/// out with minimal space requirements.
Richard Smith2d6a5672012-01-14 04:30:29 +0000297static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
298 CGBlockInfo &info) {
John McCall6b5a61b2011-02-07 10:33:21 +0000299 ASTContext &C = CGM.getContext();
300 const BlockDecl *block = info.getBlockDecl();
301
Chris Lattner5f9e2722011-07-23 10:55:15 +0000302 SmallVector<llvm::Type*, 8> elementTypes;
John McCall6b5a61b2011-02-07 10:33:21 +0000303 initializeForBlockHeader(CGM, info, elementTypes);
304
305 if (!block->hasCaptures()) {
306 info.StructureType =
307 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
308 info.CanBeGlobal = true;
309 return;
Mike Stumpe5fee252009-02-13 16:19:19 +0000310 }
Mike Stump00470a12009-03-05 08:32:30 +0000311
John McCall6b5a61b2011-02-07 10:33:21 +0000312 // Collect the layout chunks.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000313 SmallVector<BlockLayoutChunk, 16> layout;
John McCall6b5a61b2011-02-07 10:33:21 +0000314 layout.reserve(block->capturesCXXThis() +
315 (block->capture_end() - block->capture_begin()));
316
317 CharUnits maxFieldAlign;
318
319 // First, 'this'.
320 if (block->capturesCXXThis()) {
321 const DeclContext *DC = block->getDeclContext();
322 for (; isa<BlockDecl>(DC); DC = cast<BlockDecl>(DC)->getDeclContext())
323 ;
Richard Smith7a614d82011-06-11 17:19:42 +0000324 QualType thisType;
325 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
326 thisType = C.getPointerType(C.getRecordType(RD));
327 else
328 thisType = cast<CXXMethodDecl>(DC)->getThisType(C);
John McCall6b5a61b2011-02-07 10:33:21 +0000329
Jay Foadef6de3d2011-07-11 09:56:20 +0000330 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall6b5a61b2011-02-07 10:33:21 +0000331 std::pair<CharUnits,CharUnits> tinfo
332 = CGM.getContext().getTypeInfoInChars(thisType);
333 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
334
335 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first, 0, llvmType));
336 }
337
338 // Next, all the block captures.
339 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
340 ce = block->capture_end(); ci != ce; ++ci) {
341 const VarDecl *variable = ci->getVariable();
342
343 if (ci->isByRef()) {
344 // We have to copy/dispose of the __block reference.
345 info.NeedsCopyDispose = true;
346
John McCall6b5a61b2011-02-07 10:33:21 +0000347 // Just use void* instead of a pointer to the byref type.
348 QualType byRefPtrTy = C.VoidPtrTy;
349
Jay Foadef6de3d2011-07-11 09:56:20 +0000350 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000351 std::pair<CharUnits,CharUnits> tinfo
352 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
353 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
354
355 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
356 &*ci, llvmType));
357 continue;
358 }
359
360 // Otherwise, build a layout chunk with the size and alignment of
361 // the declaration.
Richard Smith2d6a5672012-01-14 04:30:29 +0000362 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall6b5a61b2011-02-07 10:33:21 +0000363 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
364 continue;
365 }
366
John McCallf85e1932011-06-15 23:02:42 +0000367 // If we have a lifetime qualifier, honor it for capture purposes.
368 // That includes *not* copying it if it's __unsafe_unretained.
369 if (Qualifiers::ObjCLifetime lifetime
370 = variable->getType().getObjCLifetime()) {
371 switch (lifetime) {
372 case Qualifiers::OCL_None: llvm_unreachable("impossible");
373 case Qualifiers::OCL_ExplicitNone:
374 case Qualifiers::OCL_Autoreleasing:
375 break;
John McCall6b5a61b2011-02-07 10:33:21 +0000376
John McCallf85e1932011-06-15 23:02:42 +0000377 case Qualifiers::OCL_Strong:
378 case Qualifiers::OCL_Weak:
379 info.NeedsCopyDispose = true;
380 }
381
382 // Block pointers require copy/dispose. So do Objective-C pointers.
383 } else if (variable->getType()->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000384 info.NeedsCopyDispose = true;
385
386 // So do types that require non-trivial copy construction.
387 } else if (ci->hasCopyExpr()) {
388 info.NeedsCopyDispose = true;
389 info.HasCXXObject = true;
390
391 // And so do types with destructors.
David Blaikie4e4d0842012-03-11 07:00:24 +0000392 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall6b5a61b2011-02-07 10:33:21 +0000393 if (const CXXRecordDecl *record =
394 variable->getType()->getAsCXXRecordDecl()) {
395 if (!record->hasTrivialDestructor()) {
396 info.HasCXXObject = true;
397 info.NeedsCopyDispose = true;
398 }
399 }
400 }
401
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000402 QualType VT = variable->getType();
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000403 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000404 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000405
John McCall6b5a61b2011-02-07 10:33:21 +0000406 maxFieldAlign = std::max(maxFieldAlign, align);
407
Jay Foadef6de3d2011-07-11 09:56:20 +0000408 llvm::Type *llvmType =
Fariborz Jahaniand8c45512011-10-31 23:44:33 +0000409 CGM.getTypes().ConvertTypeForMem(VT);
410
John McCall6b5a61b2011-02-07 10:33:21 +0000411 layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
412 }
413
414 // If that was everything, we're done here.
415 if (layout.empty()) {
416 info.StructureType =
417 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
418 info.CanBeGlobal = true;
419 return;
420 }
421
422 // Sort the layout by alignment. We have to use a stable sort here
423 // to get reproducible results. There should probably be an
424 // llvm::array_pod_stable_sort.
425 std::stable_sort(layout.begin(), layout.end());
426
427 CharUnits &blockSize = info.BlockSize;
428 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
429
430 // Assuming that the first byte in the header is maximally aligned,
431 // get the alignment of the first byte following the header.
432 CharUnits endAlign = getLowBit(blockSize);
433
434 // If the end of the header isn't satisfactorily aligned for the
435 // maximum thing, look for things that are okay with the header-end
436 // alignment, and keep appending them until we get something that's
437 // aligned right. This algorithm is only guaranteed optimal if
438 // that condition is satisfied at some point; otherwise we can get
439 // things like:
440 // header // next byte has alignment 4
441 // something_with_size_5; // next byte has alignment 1
442 // something_with_alignment_8;
443 // which has 7 bytes of padding, as opposed to the naive solution
444 // which might have less (?).
445 if (endAlign < maxFieldAlign) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000446 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000447 li = layout.begin() + 1, le = layout.end();
448
449 // Look for something that the header end is already
450 // satisfactorily aligned for.
451 for (; li != le && endAlign < li->Alignment; ++li)
452 ;
453
454 // If we found something that's naturally aligned for the end of
455 // the header, keep adding things...
456 if (li != le) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall6b5a61b2011-02-07 10:33:21 +0000458 for (; li != le; ++li) {
459 assert(endAlign >= li->Alignment);
460
461 li->setIndex(info, elementTypes.size());
462 elementTypes.push_back(li->Type);
463 blockSize += li->Size;
464 endAlign = getLowBit(blockSize);
465
466 // ...until we get to the alignment of the maximum field.
467 if (endAlign >= maxFieldAlign)
468 break;
469 }
470
471 // Don't re-append everything we just appended.
472 layout.erase(first, li);
473 }
474 }
475
John McCall6ea48412012-04-26 21:14:42 +0000476 assert(endAlign == getLowBit(blockSize));
477
John McCall6b5a61b2011-02-07 10:33:21 +0000478 // At this point, we just have to add padding if the end align still
479 // isn't aligned right.
480 if (endAlign < maxFieldAlign) {
John McCall6ea48412012-04-26 21:14:42 +0000481 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
482 CharUnits padding = newBlockSize - blockSize;
John McCall6b5a61b2011-02-07 10:33:21 +0000483
John McCall5936e332011-02-15 09:22:45 +0000484 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
485 padding.getQuantity()));
John McCall6ea48412012-04-26 21:14:42 +0000486 blockSize = newBlockSize;
John McCall6c803f72012-05-01 20:28:00 +0000487 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall6b5a61b2011-02-07 10:33:21 +0000488 }
489
John McCall6c803f72012-05-01 20:28:00 +0000490 assert(endAlign >= maxFieldAlign);
John McCall6ea48412012-04-26 21:14:42 +0000491 assert(endAlign == getLowBit(blockSize));
492
John McCall6b5a61b2011-02-07 10:33:21 +0000493 // Slam everything else on now. This works because they have
494 // strictly decreasing alignment and we expect that size is always a
495 // multiple of alignment.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000496 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall6b5a61b2011-02-07 10:33:21 +0000497 li = layout.begin(), le = layout.end(); li != le; ++li) {
498 assert(endAlign >= li->Alignment);
499 li->setIndex(info, elementTypes.size());
500 elementTypes.push_back(li->Type);
501 blockSize += li->Size;
502 endAlign = getLowBit(blockSize);
503 }
504
505 info.StructureType =
506 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
507}
508
John McCall1a343eb2011-11-10 08:15:53 +0000509/// Enter the scope of a block. This should be run at the entrance to
510/// a full-expression so that the block's cleanups are pushed at the
511/// right place in the stack.
512static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall38baeab2012-04-13 18:44:05 +0000513 assert(CGF.HaveInsertPoint());
514
John McCall1a343eb2011-11-10 08:15:53 +0000515 // Allocate the block info and place it at the head of the list.
516 CGBlockInfo &blockInfo =
517 *new CGBlockInfo(block, CGF.CurFn->getName());
518 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
519 CGF.FirstBlockInfo = &blockInfo;
520
521 // Compute information about the layout, etc., of this block,
522 // pushing cleanups as necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000523 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000524
525 // Nothing else to do if it can be global.
526 if (blockInfo.CanBeGlobal) return;
527
528 // Make the allocation for the block.
529 blockInfo.Address =
530 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
531 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
532
533 // If there are cleanups to emit, enter them (but inactive).
534 if (!blockInfo.NeedsCopyDispose) return;
535
536 // Walk through the captures (in order) and find the ones not
537 // captured by constant.
538 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
539 ce = block->capture_end(); ci != ce; ++ci) {
540 // Ignore __block captures; there's nothing special in the
541 // on-stack block that we need to do for them.
542 if (ci->isByRef()) continue;
543
544 // Ignore variables that are constant-captured.
545 const VarDecl *variable = ci->getVariable();
546 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
547 if (capture.isConstant()) continue;
548
549 // Ignore objects that aren't destructed.
550 QualType::DestructionKind dtorKind =
551 variable->getType().isDestructedType();
552 if (dtorKind == QualType::DK_none) continue;
553
554 CodeGenFunction::Destroyer *destroyer;
555
556 // Block captures count as local values and have imprecise semantics.
557 // They also can't be arrays, so need to worry about that.
558 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000559 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall1a343eb2011-11-10 08:15:53 +0000560 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000561 destroyer = CGF.getDestroyer(dtorKind);
John McCall1a343eb2011-11-10 08:15:53 +0000562 }
563
564 // GEP down to the address.
565 llvm::Value *addr = CGF.Builder.CreateStructGEP(blockInfo.Address,
566 capture.getIndex());
567
John McCall6f103ba2011-11-10 10:43:54 +0000568 // We can use that GEP as the dominating IP.
569 if (!blockInfo.DominatingIP)
570 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
571
John McCall1a343eb2011-11-10 08:15:53 +0000572 CleanupKind cleanupKind = InactiveNormalCleanup;
573 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
574 if (useArrayEHCleanup)
575 cleanupKind = InactiveNormalAndEHCleanup;
576
577 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000578 destroyer, useArrayEHCleanup);
John McCall1a343eb2011-11-10 08:15:53 +0000579
580 // Remember where that cleanup was.
581 capture.setCleanup(CGF.EHStack.stable_begin());
582 }
583}
584
585/// Enter a full-expression with a non-trivial number of objects to
586/// clean up. This is in this file because, at the moment, the only
587/// kind of cleanup object is a BlockDecl*.
588void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
589 assert(E->getNumObjects() != 0);
590 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
591 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
592 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
593 enterBlockScope(*this, *i);
594 }
595}
596
597/// Find the layout for the given block in a linked list and remove it.
598static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
599 const BlockDecl *block) {
600 while (true) {
601 assert(head && *head);
602 CGBlockInfo *cur = *head;
603
604 // If this is the block we're looking for, splice it out of the list.
605 if (cur->getBlockDecl() == block) {
606 *head = cur->NextBlockInfo;
607 return cur;
608 }
609
610 head = &cur->NextBlockInfo;
611 }
612}
613
614/// Destroy a chain of block layouts.
615void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
616 assert(head && "destroying an empty chain");
617 do {
618 CGBlockInfo *cur = head;
619 head = cur->NextBlockInfo;
620 delete cur;
621 } while (head != 0);
622}
623
John McCall6b5a61b2011-02-07 10:33:21 +0000624/// Emit a block literal expression in the current function.
625llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall1a343eb2011-11-10 08:15:53 +0000626 // If the block has no captures, we won't have a pre-computed
627 // layout for it.
628 if (!blockExpr->getBlockDecl()->hasCaptures()) {
629 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smith2d6a5672012-01-14 04:30:29 +0000630 computeBlockInfo(CGM, this, blockInfo);
John McCall1a343eb2011-11-10 08:15:53 +0000631 blockInfo.BlockExpression = blockExpr;
632 return EmitBlockLiteral(blockInfo);
633 }
John McCall6b5a61b2011-02-07 10:33:21 +0000634
John McCall1a343eb2011-11-10 08:15:53 +0000635 // Find the block info for this block and take ownership of it.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000636 OwningPtr<CGBlockInfo> blockInfo;
John McCall1a343eb2011-11-10 08:15:53 +0000637 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
638 blockExpr->getBlockDecl()));
John McCall6b5a61b2011-02-07 10:33:21 +0000639
John McCall1a343eb2011-11-10 08:15:53 +0000640 blockInfo->BlockExpression = blockExpr;
641 return EmitBlockLiteral(*blockInfo);
642}
643
644llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
645 // Using the computed layout, generate the actual block function.
Eli Friedman23f02672012-03-01 04:01:32 +0000646 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall6b5a61b2011-02-07 10:33:21 +0000647 llvm::Constant *blockFn
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000648 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000649 CurFuncDecl, LocalDeclMap,
Eli Friedman23f02672012-03-01 04:01:32 +0000650 isLambdaConv);
John McCall5936e332011-02-15 09:22:45 +0000651 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000652
653 // If there is nothing to capture, we can emit this as a global block.
654 if (blockInfo.CanBeGlobal)
655 return buildGlobalBlock(CGM, blockInfo, blockFn);
656
657 // Otherwise, we have to emit this as a local block.
658
659 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCall5936e332011-02-15 09:22:45 +0000660 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000661
662 // Build the block descriptor.
663 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
664
John McCall1a343eb2011-11-10 08:15:53 +0000665 llvm::AllocaInst *blockAddr = blockInfo.Address;
666 assert(blockAddr && "block has no address!");
John McCall6b5a61b2011-02-07 10:33:21 +0000667
668 // Compute the initial on-stack block flags.
John McCalld16c2cf2011-02-08 08:22:06 +0000669 BlockFlags flags = BLOCK_HAS_SIGNATURE;
John McCall6b5a61b2011-02-07 10:33:21 +0000670 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
671 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall64cd2322011-03-09 08:39:33 +0000672 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall6b5a61b2011-02-07 10:33:21 +0000673
674 // Initialize the block literal.
675 Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.isa"));
John McCall1a343eb2011-11-10 08:15:53 +0000676 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
John McCall6b5a61b2011-02-07 10:33:21 +0000677 Builder.CreateStructGEP(blockAddr, 1, "block.flags"));
John McCall1a343eb2011-11-10 08:15:53 +0000678 Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
John McCall6b5a61b2011-02-07 10:33:21 +0000679 Builder.CreateStructGEP(blockAddr, 2, "block.reserved"));
680 Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
681 "block.invoke"));
682 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockAddr, 4,
683 "block.descriptor"));
684
685 // Finally, capture all the values into the block.
686 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
687
688 // First, 'this'.
689 if (blockDecl->capturesCXXThis()) {
690 llvm::Value *addr = Builder.CreateStructGEP(blockAddr,
691 blockInfo.CXXThisIndex,
692 "block.captured-this.addr");
693 Builder.CreateStore(LoadCXXThis(), addr);
694 }
695
696 // Next, captured variables.
697 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
698 ce = blockDecl->capture_end(); ci != ce; ++ci) {
699 const VarDecl *variable = ci->getVariable();
700 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
701
702 // Ignore constant captures.
703 if (capture.isConstant()) continue;
704
705 QualType type = variable->getType();
706
707 // This will be a [[type]]*, except that a byref entry will just be
708 // an i8**.
709 llvm::Value *blockField =
710 Builder.CreateStructGEP(blockAddr, capture.getIndex(),
711 "block.captured");
712
713 // Compute the address of the thing we're going to move into the
714 // block literal.
715 llvm::Value *src;
Douglas Gregor29a93f82012-05-16 16:50:20 +0000716 if (BlockInfo && ci->isNested()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000717 // We need to use the capture from the enclosing block.
718 const CGBlockInfo::Capture &enclosingCapture =
719 BlockInfo->getCapture(variable);
720
721 // This is a [[type]]*, except that a byref entry wil just be an i8**.
722 src = Builder.CreateStructGEP(LoadBlockStruct(),
723 enclosingCapture.getIndex(),
724 "block.capture.addr");
Eli Friedman23f02672012-03-01 04:01:32 +0000725 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman64bee652012-02-25 02:48:22 +0000726 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman23f02672012-03-01 04:01:32 +0000727 // special; we'll simply emit it directly.
728 src = 0;
John McCall6b5a61b2011-02-07 10:33:21 +0000729 } else {
730 // This is a [[type]]*.
731 src = LocalDeclMap[variable];
732 }
733
734 // For byrefs, we just write the pointer to the byref struct into
735 // the block field. There's no need to chase the forwarding
736 // pointer at this point, since we're building something that will
737 // live a shorter life than the stack byref anyway.
738 if (ci->isByRef()) {
John McCall5936e332011-02-15 09:22:45 +0000739 // Get a void* that points to the byref struct.
John McCall6b5a61b2011-02-07 10:33:21 +0000740 if (ci->isNested())
741 src = Builder.CreateLoad(src, "byref.capture");
742 else
John McCall5936e332011-02-15 09:22:45 +0000743 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000744
John McCall5936e332011-02-15 09:22:45 +0000745 // Write that void* into the capture field.
John McCall6b5a61b2011-02-07 10:33:21 +0000746 Builder.CreateStore(src, blockField);
747
748 // If we have a copy constructor, evaluate that into the block field.
749 } else if (const Expr *copyExpr = ci->getCopyExpr()) {
Eli Friedman23f02672012-03-01 04:01:32 +0000750 if (blockDecl->isConversionFromLambda()) {
751 // If we have a lambda conversion, emit the expression
752 // directly into the block instead.
753 CharUnits Align = getContext().getTypeAlignInChars(type);
754 AggValueSlot Slot =
755 AggValueSlot::forAddr(blockField, Align, Qualifiers(),
756 AggValueSlot::IsDestructed,
757 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000758 AggValueSlot::IsNotAliased);
Eli Friedman23f02672012-03-01 04:01:32 +0000759 EmitAggExpr(copyExpr, Slot);
760 } else {
761 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
762 }
John McCall6b5a61b2011-02-07 10:33:21 +0000763
764 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000765 } else if (type->isReferenceType()) {
John McCall6b5a61b2011-02-07 10:33:21 +0000766 Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
767
768 // Otherwise, fake up a POD copy into the block field.
769 } else {
John McCallf85e1932011-06-15 23:02:42 +0000770 // Fake up a new variable so that EmitScalarInit doesn't think
771 // we're referring to the variable in its own initializer.
772 ImplicitParamDecl blockFieldPseudoVar(/*DC*/ 0, SourceLocation(),
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000773 /*name*/ 0, type);
John McCallf85e1932011-06-15 23:02:42 +0000774
John McCallbb699b02011-02-07 18:37:40 +0000775 // We use one of these or the other depending on whether the
776 // reference is nested.
John McCallf4b88a42012-03-10 09:33:50 +0000777 DeclRefExpr declRef(const_cast<VarDecl*>(variable),
778 /*refersToEnclosing*/ ci->isNested(), type,
779 VK_LValue, SourceLocation());
John McCallbb699b02011-02-07 18:37:40 +0000780
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000781 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCallf4b88a42012-03-10 09:33:50 +0000782 &declRef, VK_RValue);
John McCalla07398e2011-06-16 04:16:24 +0000783 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000784 MakeAddrLValue(blockField, type,
Eli Friedman6da2c712011-12-03 04:14:32 +0000785 getContext().getDeclAlign(variable)),
John McCalldf045202011-03-08 09:38:48 +0000786 /*captured by init*/ false);
John McCall6b5a61b2011-02-07 10:33:21 +0000787 }
788
John McCall1a343eb2011-11-10 08:15:53 +0000789 // Activate the cleanup if layout pushed one.
John McCallf85e1932011-06-15 23:02:42 +0000790 if (!ci->isByRef()) {
John McCall1a343eb2011-11-10 08:15:53 +0000791 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
792 if (cleanup.isValid())
John McCall6f103ba2011-11-10 10:43:54 +0000793 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCallf85e1932011-06-15 23:02:42 +0000794 }
John McCall6b5a61b2011-02-07 10:33:21 +0000795 }
796
797 // Cast to the converted block-pointer type, which happens (somewhat
798 // unfortunately) to be a pointer to function type.
799 llvm::Value *result =
800 Builder.CreateBitCast(blockAddr,
801 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall711c52b2011-01-05 12:14:39 +0000802
John McCall6b5a61b2011-02-07 10:33:21 +0000803 return result;
Mike Stumpe5fee252009-02-13 16:19:19 +0000804}
805
806
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000807llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000808 if (BlockDescriptorType)
809 return BlockDescriptorType;
810
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000811 llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000812 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000813
Mike Stumpab695142009-02-13 15:16:56 +0000814 // struct __block_descriptor {
815 // unsigned long reserved;
816 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000817 //
818 // // later, the following will be added
819 //
820 // struct {
821 // void (*copyHelper)();
822 // void (*copyHelper)();
823 // } helpers; // !!! optional
824 //
825 // const char *signature; // the block signature
826 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000827 // };
Chris Lattner7650d952011-06-18 22:49:11 +0000828 BlockDescriptorType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000829 llvm::StructType::create("struct.__block_descriptor",
830 UnsignedLongTy, UnsignedLongTy, NULL);
Mike Stumpab695142009-02-13 15:16:56 +0000831
John McCall6b5a61b2011-02-07 10:33:21 +0000832 // Now form a pointer to that.
833 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stumpab695142009-02-13 15:16:56 +0000834 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000835}
836
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000837llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000838 if (GenericBlockLiteralType)
839 return GenericBlockLiteralType;
840
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000841 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpa5448542009-02-13 15:32:32 +0000842
Mike Stump9b8a7972009-02-13 15:25:34 +0000843 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000844 // void *__isa;
845 // int __flags;
846 // int __reserved;
847 // void (*__invoke)(void *);
848 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000849 // };
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000850 GenericBlockLiteralType =
Chris Lattnerc1c20112011-08-12 17:43:31 +0000851 llvm::StructType::create("struct.__block_literal_generic",
852 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
853 BlockDescPtrTy, NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000854
Mike Stump9b8a7972009-02-13 15:25:34 +0000855 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000856}
857
Mike Stumpbd65cac2009-02-19 01:01:04 +0000858
Anders Carlssona1736c02009-12-24 21:13:40 +0000859RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
860 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000861 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000862 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000863
Anders Carlssonacfde802009-02-12 00:39:25 +0000864 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
865
866 // Get a pointer to the generic block literal.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000867 llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000868 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000869
870 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000871 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000872 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
873
874 // Get the function pointer from the literal.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000875 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3);
Anders Carlssonacfde802009-02-12 00:39:25 +0000876
Benjamin Kramer578faa82011-09-27 21:06:10 +0000877 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000878
Anders Carlssonacfde802009-02-12 00:39:25 +0000879 // Add the block literal.
Anders Carlssonacfde802009-02-12 00:39:25 +0000880 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000881 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000882
Anders Carlsson782f3972009-04-08 23:13:16 +0000883 QualType FnType = BPT->getPointeeType();
884
Anders Carlssonacfde802009-02-12 00:39:25 +0000885 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000886 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000887 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000888
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000889 // Load the function.
Benjamin Kramer578faa82011-09-27 21:06:10 +0000890 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000891
John McCall64cd2322011-03-09 08:39:33 +0000892 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCallde5d3c72012-02-17 03:33:10 +0000893 const CGFunctionInfo &FnInfo =
John McCall0f3d0972012-07-07 06:41:13 +0000894 CGM.getTypes().arrangeFreeFunctionCall(Args, FuncTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000896 // Cast the function pointer to the right type.
John McCallde5d3c72012-02-17 03:33:10 +0000897 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Chris Lattner2acc6e32011-07-18 04:24:23 +0000899 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000900 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Anders Carlssonacfde802009-02-12 00:39:25 +0000902 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000903 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000904}
Anders Carlssond5cab542009-02-12 17:55:02 +0000905
John McCall6b5a61b2011-02-07 10:33:21 +0000906llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
907 bool isByRef) {
908 assert(BlockInfo && "evaluating block ref without block information?");
909 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCallea1471e2010-05-20 01:18:31 +0000910
John McCall6b5a61b2011-02-07 10:33:21 +0000911 // Handle constant captures.
912 if (capture.isConstant()) return LocalDeclMap[variable];
John McCallea1471e2010-05-20 01:18:31 +0000913
John McCall6b5a61b2011-02-07 10:33:21 +0000914 llvm::Value *addr =
915 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
916 "block.capture.addr");
John McCallea1471e2010-05-20 01:18:31 +0000917
John McCall6b5a61b2011-02-07 10:33:21 +0000918 if (isByRef) {
919 // addr should be a void** right now. Load, then cast the result
920 // to byref*.
Mike Stumpdab514f2009-03-04 03:23:46 +0000921
John McCall6b5a61b2011-02-07 10:33:21 +0000922 addr = Builder.CreateLoad(addr);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000923 llvm::PointerType *byrefPointerType
John McCall6b5a61b2011-02-07 10:33:21 +0000924 = llvm::PointerType::get(BuildByRefType(variable), 0);
925 addr = Builder.CreateBitCast(addr, byrefPointerType,
926 "byref.addr");
Mike Stumpea26cb52009-10-21 03:49:08 +0000927
John McCall6b5a61b2011-02-07 10:33:21 +0000928 // Follow the forwarding pointer.
929 addr = Builder.CreateStructGEP(addr, 1, "byref.forwarding");
930 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stumpea26cb52009-10-21 03:49:08 +0000931
John McCall6b5a61b2011-02-07 10:33:21 +0000932 // Cast back to byref* and GEP over to the actual object.
933 addr = Builder.CreateBitCast(addr, byrefPointerType);
934 addr = Builder.CreateStructGEP(addr, getByRefValueLLVMField(variable),
935 variable->getNameAsString());
John McCallea1471e2010-05-20 01:18:31 +0000936 }
937
Fariborz Jahanianc637d732011-11-02 22:53:43 +0000938 if (variable->getType()->isReferenceType())
John McCall6b5a61b2011-02-07 10:33:21 +0000939 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stumpea26cb52009-10-21 03:49:08 +0000940
John McCall6b5a61b2011-02-07 10:33:21 +0000941 return addr;
Mike Stumpdab514f2009-03-04 03:23:46 +0000942}
943
Mike Stump67a64482009-02-14 22:16:35 +0000944llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +0000945CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCall5936e332011-02-15 09:22:45 +0000946 const char *name) {
John McCall1a343eb2011-11-10 08:15:53 +0000947 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
948 blockInfo.BlockExpression = blockExpr;
Mike Stumpa5448542009-02-13 15:32:32 +0000949
John McCall6b5a61b2011-02-07 10:33:21 +0000950 // Compute information about the layout, etc., of this block.
Richard Smith2d6a5672012-01-14 04:30:29 +0000951 computeBlockInfo(*this, 0, blockInfo);
Mike Stumpa5448542009-02-13 15:32:32 +0000952
John McCall6b5a61b2011-02-07 10:33:21 +0000953 // Using that metadata, generate the actual block function.
954 llvm::Constant *blockFn;
955 {
956 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCalld16c2cf2011-02-08 08:22:06 +0000957 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
958 blockInfo,
Eli Friedman64bee652012-02-25 02:48:22 +0000959 0, LocalDeclMap,
960 false);
John McCall6b5a61b2011-02-07 10:33:21 +0000961 }
John McCall5936e332011-02-15 09:22:45 +0000962 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000963
John McCalld16c2cf2011-02-08 08:22:06 +0000964 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlssond5cab542009-02-12 17:55:02 +0000965}
966
John McCall6b5a61b2011-02-07 10:33:21 +0000967static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
968 const CGBlockInfo &blockInfo,
969 llvm::Constant *blockFn) {
970 assert(blockInfo.CanBeGlobal);
971
972 // Generate the constants for the block literal initializer.
973 llvm::Constant *fields[BlockHeaderSize];
974
975 // isa
976 fields[0] = CGM.getNSConcreteGlobalBlock();
977
978 // __flags
John McCall64cd2322011-03-09 08:39:33 +0000979 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
980 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
981
John McCall5936e332011-02-15 09:22:45 +0000982 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall6b5a61b2011-02-07 10:33:21 +0000983
984 // Reserved
John McCall5936e332011-02-15 09:22:45 +0000985 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall6b5a61b2011-02-07 10:33:21 +0000986
987 // Function
988 fields[3] = blockFn;
989
990 // Descriptor
991 fields[4] = buildBlockDescriptor(CGM, blockInfo);
992
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000993 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall6b5a61b2011-02-07 10:33:21 +0000994
995 llvm::GlobalVariable *literal =
996 new llvm::GlobalVariable(CGM.getModule(),
997 init->getType(),
998 /*constant*/ true,
999 llvm::GlobalVariable::InternalLinkage,
1000 init,
1001 "__block_literal_global");
1002 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1003
1004 // Return a constant of the appropriately-casted type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001005 llvm::Type *requiredType =
John McCall6b5a61b2011-02-07 10:33:21 +00001006 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1007 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stump4e7a1f72009-02-21 20:00:35 +00001008}
1009
Mike Stump00470a12009-03-05 08:32:30 +00001010llvm::Function *
John McCall6b5a61b2011-02-07 10:33:21 +00001011CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1012 const CGBlockInfo &blockInfo,
1013 const Decl *outerFnDecl,
Eli Friedman64bee652012-02-25 02:48:22 +00001014 const DeclMapTy &ldm,
1015 bool IsLambdaConversionToBlock) {
John McCall6b5a61b2011-02-07 10:33:21 +00001016 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel963dfbd2009-04-15 21:51:44 +00001017
Devang Patel6d1155b2011-03-07 21:53:18 +00001018 // Check if we should generate debug info for this block function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001019 maybeInitializeDebugInfo();
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001020 CurGD = GD;
1021
John McCall6b5a61b2011-02-07 10:33:21 +00001022 BlockInfo = &blockInfo;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Mike Stump7f28a9c2009-03-13 23:34:28 +00001024 // Arrange for local static and local extern declarations to appear
John McCall6b5a61b2011-02-07 10:33:21 +00001025 // to be local to this function as well, in case they're directly
1026 // referenced in a block.
1027 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
1028 const VarDecl *var = dyn_cast<VarDecl>(i->first);
1029 if (var && !var->hasLocalStorage())
1030 LocalDeclMap[var] = i->second;
Mike Stump7f28a9c2009-03-13 23:34:28 +00001031 }
1032
John McCall6b5a61b2011-02-07 10:33:21 +00001033 // Begin building the function declaration.
Eli Friedman48f91222009-03-28 03:24:54 +00001034
John McCall6b5a61b2011-02-07 10:33:21 +00001035 // Build the argument list.
1036 FunctionArgList args;
Mike Stumpa5448542009-02-13 15:32:32 +00001037
John McCall6b5a61b2011-02-07 10:33:21 +00001038 // The first argument is the block pointer. Just take it as a void*
1039 // and cast it later.
1040 QualType selfTy = getContext().VoidPtrTy;
Mike Stumpea26cb52009-10-21 03:49:08 +00001041 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +00001042
John McCall8178df32011-02-22 22:38:33 +00001043 ImplicitParamDecl selfDecl(const_cast<BlockDecl*>(blockDecl),
1044 SourceLocation(), II, selfTy);
John McCalld26bc762011-03-09 04:27:21 +00001045 args.push_back(&selfDecl);
Mike Stumpea26cb52009-10-21 03:49:08 +00001046
John McCall6b5a61b2011-02-07 10:33:21 +00001047 // Now add the rest of the parameters.
1048 for (BlockDecl::param_const_iterator i = blockDecl->param_begin(),
1049 e = blockDecl->param_end(); i != e; ++i)
John McCalld26bc762011-03-09 04:27:21 +00001050 args.push_back(*i);
John McCallea1471e2010-05-20 01:18:31 +00001051
John McCall6b5a61b2011-02-07 10:33:21 +00001052 // Create the function declaration.
John McCallde5d3c72012-02-17 03:33:10 +00001053 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCall6b5a61b2011-02-07 10:33:21 +00001054 const CGFunctionInfo &fnInfo =
John McCallde5d3c72012-02-17 03:33:10 +00001055 CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), args,
1056 fnType->getExtInfo(),
1057 fnType->isVariadic());
John McCall64cd2322011-03-09 08:39:33 +00001058 if (CGM.ReturnTypeUsesSRet(fnInfo))
1059 blockInfo.UsesStret = true;
1060
John McCallde5d3c72012-02-17 03:33:10 +00001061 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001062
John McCall6b5a61b2011-02-07 10:33:21 +00001063 MangleBuffer name;
1064 CGM.getBlockMangledName(GD, name, blockDecl);
1065 llvm::Function *fn =
1066 llvm::Function::Create(fnLLVMType, llvm::GlobalValue::InternalLinkage,
1067 name.getString(), &CGM.getModule());
1068 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpa5448542009-02-13 15:32:32 +00001069
John McCall6b5a61b2011-02-07 10:33:21 +00001070 // Begin generating the function.
John McCalld26bc762011-03-09 04:27:21 +00001071 StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
Devang Patel3f4cb252011-03-25 21:26:13 +00001072 blockInfo.getBlockExpr()->getBody()->getLocStart());
John McCall6b5a61b2011-02-07 10:33:21 +00001073 CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
Mike Stumpa5448542009-02-13 15:32:32 +00001074
John McCall8178df32011-02-22 22:38:33 +00001075 // Okay. Undo some of what StartFunction did.
1076
1077 // Pull the 'self' reference out of the local decl map.
1078 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1079 LocalDeclMap.erase(&selfDecl);
John McCall6b5a61b2011-02-07 10:33:21 +00001080 BlockPointer = Builder.CreateBitCast(blockAddr,
1081 blockInfo.StructureType->getPointerTo(),
1082 "block");
Anders Carlssond5cab542009-02-12 17:55:02 +00001083
John McCallea1471e2010-05-20 01:18:31 +00001084 // If we have a C++ 'this' reference, go ahead and force it into
1085 // existence now.
John McCall6b5a61b2011-02-07 10:33:21 +00001086 if (blockDecl->capturesCXXThis()) {
1087 llvm::Value *addr = Builder.CreateStructGEP(BlockPointer,
1088 blockInfo.CXXThisIndex,
1089 "block.captured-this");
1090 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCallea1471e2010-05-20 01:18:31 +00001091 }
1092
John McCall6b5a61b2011-02-07 10:33:21 +00001093 // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
1094 // appease it.
1095 if (const ObjCMethodDecl *method
1096 = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
1097 const VarDecl *self = method->getSelfDecl();
1098
1099 // There might not be a capture for 'self', but if there is...
1100 if (blockInfo.Captures.count(self)) {
1101 const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
1102 llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
1103 capture.getIndex(),
1104 "block.captured-self");
1105 LocalDeclMap[self] = selfAddr;
1106 }
1107 }
1108
1109 // Also force all the constant captures.
1110 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1111 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1112 const VarDecl *variable = ci->getVariable();
1113 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1114 if (!capture.isConstant()) continue;
1115
1116 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1117
1118 llvm::AllocaInst *alloca =
1119 CreateMemTemp(variable->getType(), "block.captured-const");
1120 alloca->setAlignment(align);
1121
1122 Builder.CreateStore(capture.getConstant(), alloca, align);
1123
1124 LocalDeclMap[variable] = alloca;
John McCallee504292010-05-21 04:11:14 +00001125 }
1126
John McCallf4b88a42012-03-10 09:33:50 +00001127 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001128 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1129 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1130 --entry_ptr;
1131
Eli Friedman64bee652012-02-25 02:48:22 +00001132 if (IsLambdaConversionToBlock)
1133 EmitLambdaBlockInvokeBody();
1134 else
1135 EmitStmt(blockDecl->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +00001136
Mike Stumpde8c5c72009-10-01 00:27:30 +00001137 // Remember where we were...
1138 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +00001139
Mike Stumpde8c5c72009-10-01 00:27:30 +00001140 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +00001141 ++entry_ptr;
1142 Builder.SetInsertPoint(entry, entry_ptr);
1143
John McCallf4b88a42012-03-10 09:33:50 +00001144 // Emit debug information for all the DeclRefExprs.
John McCall6b5a61b2011-02-07 10:33:21 +00001145 // FIXME: also for 'this'
Mike Stumpb1a6e682009-09-30 02:43:10 +00001146 if (CGDebugInfo *DI = getDebugInfo()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001147 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1148 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1149 const VarDecl *variable = ci->getVariable();
Eric Christopher73fb3502011-10-13 21:45:18 +00001150 DI->EmitLocation(Builder, variable->getLocation());
John McCall6b5a61b2011-02-07 10:33:21 +00001151
Douglas Gregor4cdad312012-10-23 20:05:01 +00001152 if (CGM.getCodeGenOpts().getDebugInfo()
1153 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001154 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1155 if (capture.isConstant()) {
1156 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1157 Builder);
1158 continue;
1159 }
John McCall6b5a61b2011-02-07 10:33:21 +00001160
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001161 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointer,
1162 Builder, blockInfo);
1163 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001164 }
Mike Stumpb1a6e682009-09-30 02:43:10 +00001165 }
John McCall6b5a61b2011-02-07 10:33:21 +00001166
Mike Stumpde8c5c72009-10-01 00:27:30 +00001167 // And resume where we left off.
1168 if (resume == 0)
1169 Builder.ClearInsertionPoint();
1170 else
1171 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +00001172
John McCall6b5a61b2011-02-07 10:33:21 +00001173 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +00001174
John McCall6b5a61b2011-02-07 10:33:21 +00001175 return fn;
Anders Carlssond5cab542009-02-12 17:55:02 +00001176}
Mike Stumpa99038c2009-02-28 09:07:16 +00001177
John McCall6b5a61b2011-02-07 10:33:21 +00001178/*
1179 notes.push_back(HelperInfo());
1180 HelperInfo &note = notes.back();
1181 note.index = capture.getIndex();
1182 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1183 note.cxxbar_import = ci->getCopyExpr();
Mike Stumpa99038c2009-02-28 09:07:16 +00001184
John McCall6b5a61b2011-02-07 10:33:21 +00001185 if (ci->isByRef()) {
1186 note.flag = BLOCK_FIELD_IS_BYREF;
1187 if (type.isObjCGCWeak())
1188 note.flag |= BLOCK_FIELD_IS_WEAK;
1189 } else if (type->isBlockPointerType()) {
1190 note.flag = BLOCK_FIELD_IS_BLOCK;
1191 } else {
1192 note.flag = BLOCK_FIELD_IS_OBJECT;
1193 }
1194 */
Mike Stumpa99038c2009-02-28 09:07:16 +00001195
Mike Stump00470a12009-03-05 08:32:30 +00001196
Mike Stumpa99038c2009-02-28 09:07:16 +00001197
John McCall6b5a61b2011-02-07 10:33:21 +00001198llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001199CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001200 ASTContext &C = getContext();
1201
1202 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001203 ImplicitParamDecl dstDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1204 args.push_back(&dstDecl);
1205 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1206 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Mike Stumpa4f668f2009-03-06 01:33:24 +00001208 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001209 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1210 FunctionType::ExtInfo(),
1211 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001212
John McCall6b5a61b2011-02-07 10:33:21 +00001213 // FIXME: it would be nice if these were mergeable with things with
1214 // identical semantics.
John McCallde5d3c72012-02-17 03:33:10 +00001215 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001216
1217 llvm::Function *Fn =
1218 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001219 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001220
1221 IdentifierInfo *II
1222 = &CGM.getContext().Idents.get("__copy_helper_block_");
1223
Devang Patel58dc5ca2011-05-02 20:37:08 +00001224 // Check if we should generate debug info for this block helper function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001225 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001226
John McCall6b5a61b2011-02-07 10:33:21 +00001227 FunctionDecl *FD = FunctionDecl::Create(C,
1228 C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001229 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001230 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001231 SC_Static,
1232 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001233 false,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001234 false);
John McCalld26bc762011-03-09 04:27:21 +00001235 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +00001236
Chris Lattner2acc6e32011-07-18 04:24:23 +00001237 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump08920992009-03-07 02:35:30 +00001238
John McCalld26bc762011-03-09 04:27:21 +00001239 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001240 src = Builder.CreateLoad(src);
1241 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stump08920992009-03-07 02:35:30 +00001242
John McCalld26bc762011-03-09 04:27:21 +00001243 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001244 dst = Builder.CreateLoad(dst);
1245 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stump08920992009-03-07 02:35:30 +00001246
John McCall6b5a61b2011-02-07 10:33:21 +00001247 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stump08920992009-03-07 02:35:30 +00001248
John McCall6b5a61b2011-02-07 10:33:21 +00001249 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1250 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1251 const VarDecl *variable = ci->getVariable();
1252 QualType type = variable->getType();
Mike Stump08920992009-03-07 02:35:30 +00001253
John McCall6b5a61b2011-02-07 10:33:21 +00001254 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1255 if (capture.isConstant()) continue;
1256
1257 const Expr *copyExpr = ci->getCopyExpr();
John McCallf85e1932011-06-15 23:02:42 +00001258 BlockFieldFlags flags;
1259
John McCall015f33b2012-10-17 02:28:37 +00001260 bool useARCWeakCopy = false;
1261 bool useARCStrongCopy = false;
John McCall6b5a61b2011-02-07 10:33:21 +00001262
1263 if (copyExpr) {
1264 assert(!ci->isByRef());
1265 // don't bother computing flags
John McCallf85e1932011-06-15 23:02:42 +00001266
John McCall6b5a61b2011-02-07 10:33:21 +00001267 } else if (ci->isByRef()) {
1268 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001269 if (type.isObjCGCWeak())
1270 flags |= BLOCK_FIELD_IS_WEAK;
John McCall6b5a61b2011-02-07 10:33:21 +00001271
John McCallf85e1932011-06-15 23:02:42 +00001272 } else if (type->isObjCRetainableType()) {
1273 flags = BLOCK_FIELD_IS_OBJECT;
John McCall015f33b2012-10-17 02:28:37 +00001274 bool isBlockPointer = type->isBlockPointerType();
1275 if (isBlockPointer)
John McCallf85e1932011-06-15 23:02:42 +00001276 flags = BLOCK_FIELD_IS_BLOCK;
1277
1278 // Special rules for ARC captures:
David Blaikie4e4d0842012-03-11 07:00:24 +00001279 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001280 Qualifiers qs = type.getQualifiers();
1281
John McCall015f33b2012-10-17 02:28:37 +00001282 // We need to register __weak direct captures with the runtime.
1283 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1284 useARCWeakCopy = true;
John McCallf85e1932011-06-15 23:02:42 +00001285
John McCall015f33b2012-10-17 02:28:37 +00001286 // We need to retain the copied value for __strong direct captures.
1287 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1288 // If it's a block pointer, we have to copy the block and
1289 // assign that to the destination pointer, so we might as
1290 // well use _Block_object_assign. Otherwise we can avoid that.
1291 if (!isBlockPointer)
1292 useARCStrongCopy = true;
1293
1294 // Otherwise the memcpy is fine.
1295 } else {
1296 continue;
1297 }
1298
1299 // Non-ARC captures of retainable pointers are strong and
1300 // therefore require a call to _Block_object_assign.
1301 } else {
1302 // fall through
John McCallf85e1932011-06-15 23:02:42 +00001303 }
1304 } else {
1305 continue;
1306 }
John McCall6b5a61b2011-02-07 10:33:21 +00001307
1308 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001309 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
1310 llvm::Value *dstField = Builder.CreateStructGEP(dst, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001311
1312 // If there's an explicit copy expression, we do that.
1313 if (copyExpr) {
John McCalld16c2cf2011-02-08 08:22:06 +00001314 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCall015f33b2012-10-17 02:28:37 +00001315 } else if (useARCWeakCopy) {
John McCallf85e1932011-06-15 23:02:42 +00001316 EmitARCCopyWeak(dstField, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001317 } else {
1318 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCall015f33b2012-10-17 02:28:37 +00001319 if (useARCStrongCopy) {
1320 // At -O0, store null into the destination field (so that the
1321 // storeStrong doesn't over-release) and then call storeStrong.
1322 // This is a workaround to not having an initStrong call.
1323 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1324 llvm::PointerType *ty = cast<llvm::PointerType>(srcValue->getType());
1325 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1326 Builder.CreateStore(null, dstField);
1327 EmitARCStoreStrongCall(dstField, srcValue, true);
1328
1329 // With optimization enabled, take advantage of the fact that
1330 // the blocks runtime guarantees a memcpy of the block data, and
1331 // just emit a retain of the src field.
1332 } else {
1333 EmitARCRetainNonBlock(srcValue);
1334
1335 // We don't need this anymore, so kill it. It's not quite
1336 // worth the annoyance to avoid creating it in the first place.
1337 cast<llvm::Instruction>(dstField)->eraseFromParent();
1338 }
1339 } else {
1340 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1341 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
1342 Builder.CreateCall3(CGM.getBlockObjectAssign(), dstAddr, srcValue,
1343 llvm::ConstantInt::get(Int32Ty, flags.getBitMask()));
1344 }
Mike Stump08920992009-03-07 02:35:30 +00001345 }
1346 }
1347
John McCalld16c2cf2011-02-08 08:22:06 +00001348 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001349
John McCall5936e332011-02-15 09:22:45 +00001350 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +00001351}
1352
John McCall6b5a61b2011-02-07 10:33:21 +00001353llvm::Constant *
John McCalld16c2cf2011-02-08 08:22:06 +00001354CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall6b5a61b2011-02-07 10:33:21 +00001355 ASTContext &C = getContext();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001356
John McCall6b5a61b2011-02-07 10:33:21 +00001357 FunctionArgList args;
John McCalld26bc762011-03-09 04:27:21 +00001358 ImplicitParamDecl srcDecl(0, SourceLocation(), 0, C.VoidPtrTy);
1359 args.push_back(&srcDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Mike Stumpa4f668f2009-03-06 01:33:24 +00001361 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001362 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
1363 FunctionType::ExtInfo(),
1364 /*variadic*/ false);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001365
Mike Stump3899a7f2009-06-05 23:26:36 +00001366 // FIXME: We'd like to put these into a mergable by content, with
1367 // internal linkage.
John McCallde5d3c72012-02-17 03:33:10 +00001368 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001369
1370 llvm::Function *Fn =
1371 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001372 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001373
Devang Patel58dc5ca2011-05-02 20:37:08 +00001374 // Check if we should generate debug info for this block destroy function.
Alexey Samsonova240df22012-10-16 07:22:28 +00001375 maybeInitializeDebugInfo();
Devang Patel58dc5ca2011-05-02 20:37:08 +00001376
Mike Stumpa4f668f2009-03-06 01:33:24 +00001377 IdentifierInfo *II
1378 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1379
John McCall6b5a61b2011-02-07 10:33:21 +00001380 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001381 SourceLocation(),
John McCall6b5a61b2011-02-07 10:33:21 +00001382 SourceLocation(), II, C.VoidTy, 0,
John McCalld931b082010-08-26 03:08:43 +00001383 SC_Static,
1384 SC_None,
Eric Christophere5bbebb2012-04-12 00:35:04 +00001385 false, false);
John McCalld26bc762011-03-09 04:27:21 +00001386 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001387
Chris Lattner2acc6e32011-07-18 04:24:23 +00001388 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump1edf6b62009-03-07 02:53:18 +00001389
John McCalld26bc762011-03-09 04:27:21 +00001390 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCalld16c2cf2011-02-08 08:22:06 +00001391 src = Builder.CreateLoad(src);
1392 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump1edf6b62009-03-07 02:53:18 +00001393
John McCall6b5a61b2011-02-07 10:33:21 +00001394 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1395
John McCalld16c2cf2011-02-08 08:22:06 +00001396 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall6b5a61b2011-02-07 10:33:21 +00001397
1398 for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
1399 ce = blockDecl->capture_end(); ci != ce; ++ci) {
1400 const VarDecl *variable = ci->getVariable();
1401 QualType type = variable->getType();
1402
1403 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1404 if (capture.isConstant()) continue;
1405
John McCalld16c2cf2011-02-08 08:22:06 +00001406 BlockFieldFlags flags;
John McCall6b5a61b2011-02-07 10:33:21 +00001407 const CXXDestructorDecl *dtor = 0;
1408
John McCall015f33b2012-10-17 02:28:37 +00001409 bool useARCWeakDestroy = false;
1410 bool useARCStrongDestroy = false;
John McCallf85e1932011-06-15 23:02:42 +00001411
John McCall6b5a61b2011-02-07 10:33:21 +00001412 if (ci->isByRef()) {
1413 flags = BLOCK_FIELD_IS_BYREF;
John McCallf85e1932011-06-15 23:02:42 +00001414 if (type.isObjCGCWeak())
1415 flags |= BLOCK_FIELD_IS_WEAK;
1416 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1417 if (record->hasTrivialDestructor())
1418 continue;
1419 dtor = record->getDestructor();
1420 } else if (type->isObjCRetainableType()) {
John McCall6b5a61b2011-02-07 10:33:21 +00001421 flags = BLOCK_FIELD_IS_OBJECT;
John McCallf85e1932011-06-15 23:02:42 +00001422 if (type->isBlockPointerType())
1423 flags = BLOCK_FIELD_IS_BLOCK;
John McCall6b5a61b2011-02-07 10:33:21 +00001424
John McCallf85e1932011-06-15 23:02:42 +00001425 // Special rules for ARC captures.
David Blaikie4e4d0842012-03-11 07:00:24 +00001426 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001427 Qualifiers qs = type.getQualifiers();
1428
1429 // Don't generate special dispose logic for a captured object
1430 // unless it's __strong or __weak.
1431 if (!qs.hasStrongOrWeakObjCLifetime())
1432 continue;
1433
1434 // Support __weak direct captures.
1435 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCall015f33b2012-10-17 02:28:37 +00001436 useARCWeakDestroy = true;
1437
1438 // Tools really want us to use objc_storeStrong here.
1439 else
1440 useARCStrongDestroy = true;
John McCallf85e1932011-06-15 23:02:42 +00001441 }
1442 } else {
1443 continue;
1444 }
John McCall6b5a61b2011-02-07 10:33:21 +00001445
1446 unsigned index = capture.getIndex();
John McCalld16c2cf2011-02-08 08:22:06 +00001447 llvm::Value *srcField = Builder.CreateStructGEP(src, index);
John McCall6b5a61b2011-02-07 10:33:21 +00001448
1449 // If there's an explicit copy expression, we do that.
1450 if (dtor) {
John McCalld16c2cf2011-02-08 08:22:06 +00001451 PushDestructorCleanup(dtor, srcField);
John McCall6b5a61b2011-02-07 10:33:21 +00001452
John McCallf85e1932011-06-15 23:02:42 +00001453 // If this is a __weak capture, emit the release directly.
John McCall015f33b2012-10-17 02:28:37 +00001454 } else if (useARCWeakDestroy) {
John McCallf85e1932011-06-15 23:02:42 +00001455 EmitARCDestroyWeak(srcField);
1456
John McCall015f33b2012-10-17 02:28:37 +00001457 // Destroy strong objects with a call if requested.
1458 } else if (useARCStrongDestroy) {
1459 EmitARCDestroyStrong(srcField, /*precise*/ false);
1460
John McCall6b5a61b2011-02-07 10:33:21 +00001461 // Otherwise we call _Block_object_dispose. It wouldn't be too
1462 // hard to just emit this as a cleanup if we wanted to make sure
1463 // that things were done in reverse.
1464 } else {
1465 llvm::Value *value = Builder.CreateLoad(srcField);
John McCall5936e332011-02-15 09:22:45 +00001466 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall6b5a61b2011-02-07 10:33:21 +00001467 BuildBlockRelease(value, flags);
1468 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001469 }
1470
John McCall6b5a61b2011-02-07 10:33:21 +00001471 cleanups.ForceCleanup();
1472
John McCalld16c2cf2011-02-08 08:22:06 +00001473 FinishFunction();
Mike Stumpa4f668f2009-03-06 01:33:24 +00001474
John McCall5936e332011-02-15 09:22:45 +00001475 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001476}
1477
John McCallf0c11f72011-03-31 08:03:29 +00001478namespace {
1479
1480/// Emits the copy/dispose helper functions for a __block object of id type.
1481class ObjectByrefHelpers : public CodeGenModule::ByrefHelpers {
1482 BlockFieldFlags Flags;
1483
1484public:
1485 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1486 : ByrefHelpers(alignment), Flags(flags) {}
1487
John McCall36170192011-03-31 09:19:20 +00001488 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1489 llvm::Value *srcField) {
John McCallf0c11f72011-03-31 08:03:29 +00001490 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1491
1492 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1493 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1494
1495 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1496
1497 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1498 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
1499 CGF.Builder.CreateCall3(fn, destField, srcValue, flagsVal);
1500 }
1501
1502 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1503 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1504 llvm::Value *value = CGF.Builder.CreateLoad(field);
1505
1506 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1507 }
1508
1509 void profileImpl(llvm::FoldingSetNodeID &id) const {
1510 id.AddInteger(Flags.getBitMask());
1511 }
1512};
1513
John McCallf85e1932011-06-15 23:02:42 +00001514/// Emits the copy/dispose helpers for an ARC __block __weak variable.
1515class ARCWeakByrefHelpers : public CodeGenModule::ByrefHelpers {
1516public:
1517 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1518
1519 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1520 llvm::Value *srcField) {
1521 CGF.EmitARCMoveWeak(destField, srcField);
1522 }
1523
1524 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1525 CGF.EmitARCDestroyWeak(field);
1526 }
1527
1528 void profileImpl(llvm::FoldingSetNodeID &id) const {
1529 // 0 is distinguishable from all pointers and byref flags
1530 id.AddInteger(0);
1531 }
1532};
1533
1534/// Emits the copy/dispose helpers for an ARC __block __strong variable
1535/// that's not of block-pointer type.
1536class ARCStrongByrefHelpers : public CodeGenModule::ByrefHelpers {
1537public:
1538 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1539
1540 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1541 llvm::Value *srcField) {
1542 // Do a "move" by copying the value and then zeroing out the old
1543 // variable.
1544
John McCalla59e4b72011-11-09 03:17:26 +00001545 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1546 value->setAlignment(Alignment.getQuantity());
1547
John McCallf85e1932011-06-15 23:02:42 +00001548 llvm::Value *null =
1549 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCalla59e4b72011-11-09 03:17:26 +00001550
1551 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1552 store->setAlignment(Alignment.getQuantity());
1553
1554 store = CGF.Builder.CreateStore(null, srcField);
1555 store->setAlignment(Alignment.getQuantity());
John McCallf85e1932011-06-15 23:02:42 +00001556 }
1557
1558 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001559 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001560 }
1561
1562 void profileImpl(llvm::FoldingSetNodeID &id) const {
1563 // 1 is distinguishable from all pointers and byref flags
1564 id.AddInteger(1);
1565 }
1566};
1567
John McCalla59e4b72011-11-09 03:17:26 +00001568/// Emits the copy/dispose helpers for an ARC __block __strong
1569/// variable that's of block-pointer type.
1570class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
1571public:
1572 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1573
1574 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1575 llvm::Value *srcField) {
1576 // Do the copy with objc_retainBlock; that's all that
1577 // _Block_object_assign would do anyway, and we'd have to pass the
1578 // right arguments to make sure it doesn't get no-op'ed.
1579 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1580 oldValue->setAlignment(Alignment.getQuantity());
1581
1582 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1583
1584 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1585 store->setAlignment(Alignment.getQuantity());
1586 }
1587
1588 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
John McCall015f33b2012-10-17 02:28:37 +00001589 CGF.EmitARCDestroyStrong(field, /*precise*/ false);
John McCalla59e4b72011-11-09 03:17:26 +00001590 }
1591
1592 void profileImpl(llvm::FoldingSetNodeID &id) const {
1593 // 2 is distinguishable from all pointers and byref flags
1594 id.AddInteger(2);
1595 }
1596};
1597
John McCallf0c11f72011-03-31 08:03:29 +00001598/// Emits the copy/dispose helpers for a __block variable with a
1599/// nontrivial copy constructor or destructor.
1600class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
1601 QualType VarType;
1602 const Expr *CopyExpr;
1603
1604public:
1605 CXXByrefHelpers(CharUnits alignment, QualType type,
1606 const Expr *copyExpr)
1607 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1608
1609 bool needsCopy() const { return CopyExpr != 0; }
1610 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
1611 llvm::Value *srcField) {
1612 if (!CopyExpr) return;
1613 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1614 }
1615
1616 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
1617 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1618 CGF.PushDestructorCleanup(VarType, field);
1619 CGF.PopCleanupBlocks(cleanupDepth);
1620 }
1621
1622 void profileImpl(llvm::FoldingSetNodeID &id) const {
1623 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1624 }
1625};
1626} // end anonymous namespace
1627
1628static llvm::Constant *
1629generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001630 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001631 CodeGenModule::ByrefHelpers &byrefInfo) {
1632 ASTContext &Context = CGF.getContext();
1633
1634 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001635
John McCalld26bc762011-03-09 04:27:21 +00001636 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001637 ImplicitParamDecl dst(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001638 args.push_back(&dst);
Mike Stumpee094222009-03-06 06:12:24 +00001639
John McCallf0c11f72011-03-31 08:03:29 +00001640 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001641 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Mike Stump45031c02009-03-06 02:29:21 +00001643 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001644 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1645 FunctionType::ExtInfo(),
1646 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001647
John McCallf0c11f72011-03-31 08:03:29 +00001648 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001649 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001650
Mike Stump3899a7f2009-06-05 23:26:36 +00001651 // FIXME: We'd like to put these into a mergable by content, with
1652 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001653 llvm::Function *Fn =
1654 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf0c11f72011-03-31 08:03:29 +00001655 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001656
1657 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001658 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stump45031c02009-03-06 02:29:21 +00001659
John McCallf0c11f72011-03-31 08:03:29 +00001660 FunctionDecl *FD = FunctionDecl::Create(Context,
1661 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001662 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001663 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001664 SC_Static,
1665 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001666 false, false);
John McCallf85e1932011-06-15 23:02:42 +00001667
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001668 // Initialize debug info if necessary.
1669 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001670 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001671
John McCallf0c11f72011-03-31 08:03:29 +00001672 if (byrefInfo.needsCopy()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001673 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpee094222009-03-06 06:12:24 +00001674
John McCallf0c11f72011-03-31 08:03:29 +00001675 // dst->x
1676 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1677 destField = CGF.Builder.CreateLoad(destField);
1678 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
1679 destField = CGF.Builder.CreateStructGEP(destField, 6, "x");
Mike Stump45031c02009-03-06 02:29:21 +00001680
John McCallf0c11f72011-03-31 08:03:29 +00001681 // src->x
1682 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1683 srcField = CGF.Builder.CreateLoad(srcField);
1684 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
1685 srcField = CGF.Builder.CreateStructGEP(srcField, 6, "x");
1686
1687 byrefInfo.emitCopy(CGF, destField, srcField);
1688 }
1689
1690 CGF.FinishFunction();
1691
1692 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001693}
1694
John McCallf0c11f72011-03-31 08:03:29 +00001695/// Build the copy helper for a __block variable.
1696static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001697 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001698 CodeGenModule::ByrefHelpers &info) {
1699 CodeGenFunction CGF(CGM);
1700 return generateByrefCopyHelper(CGF, byrefType, info);
1701}
1702
1703/// Generate code for a __block variable's dispose helper.
1704static llvm::Constant *
1705generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001706 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001707 CodeGenModule::ByrefHelpers &byrefInfo) {
1708 ASTContext &Context = CGF.getContext();
1709 QualType R = Context.VoidTy;
Mike Stump45031c02009-03-06 02:29:21 +00001710
John McCalld26bc762011-03-09 04:27:21 +00001711 FunctionArgList args;
John McCallf0c11f72011-03-31 08:03:29 +00001712 ImplicitParamDecl src(0, SourceLocation(), 0, Context.VoidPtrTy);
John McCalld26bc762011-03-09 04:27:21 +00001713 args.push_back(&src);
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Mike Stump45031c02009-03-06 02:29:21 +00001715 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00001716 CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
1717 FunctionType::ExtInfo(),
1718 /*variadic*/ false);
Mike Stump45031c02009-03-06 02:29:21 +00001719
John McCallf0c11f72011-03-31 08:03:29 +00001720 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCallde5d3c72012-02-17 03:33:10 +00001721 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stump45031c02009-03-06 02:29:21 +00001722
Mike Stump3899a7f2009-06-05 23:26:36 +00001723 // FIXME: We'd like to put these into a mergable by content, with
1724 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001725 llvm::Function *Fn =
1726 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001727 "__Block_byref_object_dispose_",
John McCallf0c11f72011-03-31 08:03:29 +00001728 &CGF.CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001729
1730 IdentifierInfo *II
John McCallf0c11f72011-03-31 08:03:29 +00001731 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stump45031c02009-03-06 02:29:21 +00001732
John McCallf0c11f72011-03-31 08:03:29 +00001733 FunctionDecl *FD = FunctionDecl::Create(Context,
1734 Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001735 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001736 SourceLocation(), II, R, 0,
John McCalld931b082010-08-26 03:08:43 +00001737 SC_Static,
1738 SC_None,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00001739 false, false);
Alexey Samsonov34b41f82012-10-25 10:18:50 +00001740 // Initialize debug info if necessary.
1741 CGF.maybeInitializeDebugInfo();
John McCallf0c11f72011-03-31 08:03:29 +00001742 CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001743
John McCallf0c11f72011-03-31 08:03:29 +00001744 if (byrefInfo.needsDispose()) {
1745 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1746 V = CGF.Builder.CreateLoad(V);
1747 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
1748 V = CGF.Builder.CreateStructGEP(V, 6, "x");
John McCalld16c2cf2011-02-08 08:22:06 +00001749
John McCallf0c11f72011-03-31 08:03:29 +00001750 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001751 }
Mike Stump45031c02009-03-06 02:29:21 +00001752
John McCallf0c11f72011-03-31 08:03:29 +00001753 CGF.FinishFunction();
John McCalld16c2cf2011-02-08 08:22:06 +00001754
John McCallf0c11f72011-03-31 08:03:29 +00001755 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stump45031c02009-03-06 02:29:21 +00001756}
1757
John McCallf0c11f72011-03-31 08:03:29 +00001758/// Build the dispose helper for a __block variable.
1759static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001760 llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001761 CodeGenModule::ByrefHelpers &info) {
1762 CodeGenFunction CGF(CGM);
1763 return generateByrefDisposeHelper(CGF, byrefType, info);
Mike Stump45031c02009-03-06 02:29:21 +00001764}
1765
John McCallf0c11f72011-03-31 08:03:29 +00001766///
1767template <class T> static T *buildByrefHelpers(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001768 llvm::StructType &byrefTy,
John McCallf0c11f72011-03-31 08:03:29 +00001769 T &byrefInfo) {
1770 // Increase the field's alignment to be at least pointer alignment,
1771 // since the layout of the byref struct will guarantee at least that.
1772 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1773 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1774
1775 llvm::FoldingSetNodeID id;
1776 byrefInfo.Profile(id);
1777
1778 void *insertPos;
1779 CodeGenModule::ByrefHelpers *node
1780 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1781 if (node) return static_cast<T*>(node);
1782
1783 byrefInfo.CopyHelper = buildByrefCopyHelper(CGM, byrefTy, byrefInfo);
1784 byrefInfo.DisposeHelper = buildByrefDisposeHelper(CGM, byrefTy, byrefInfo);
1785
1786 T *copy = new (CGM.getContext()) T(byrefInfo);
1787 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1788 return copy;
1789}
1790
1791CodeGenModule::ByrefHelpers *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001792CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf0c11f72011-03-31 08:03:29 +00001793 const AutoVarEmission &emission) {
1794 const VarDecl &var = *emission.Variable;
1795 QualType type = var.getType();
1796
1797 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1798 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
1799 if (!copyExpr && record->hasTrivialDestructor()) return 0;
1800
1801 CXXByrefHelpers byrefInfo(emission.Alignment, type, copyExpr);
1802 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1803 }
1804
John McCallf85e1932011-06-15 23:02:42 +00001805 // Otherwise, if we don't have a retainable type, there's nothing to do.
1806 // that the runtime does extra copies.
1807 if (!type->isObjCRetainableType()) return 0;
1808
1809 Qualifiers qs = type.getQualifiers();
1810
1811 // If we have lifetime, that dominates.
1812 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001813 assert(getLangOpts().ObjCAutoRefCount);
John McCallf85e1932011-06-15 23:02:42 +00001814
1815 switch (lifetime) {
1816 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1817
1818 // These are just bits as far as the runtime is concerned.
1819 case Qualifiers::OCL_ExplicitNone:
1820 case Qualifiers::OCL_Autoreleasing:
1821 return 0;
1822
1823 // Tell the runtime that this is ARC __weak, called by the
1824 // byref routines.
1825 case Qualifiers::OCL_Weak: {
1826 ARCWeakByrefHelpers byrefInfo(emission.Alignment);
1827 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1828 }
1829
1830 // ARC __strong __block variables need to be retained.
1831 case Qualifiers::OCL_Strong:
John McCalla59e4b72011-11-09 03:17:26 +00001832 // Block pointers need to be copied, and there's no direct
1833 // transfer possible.
John McCallf85e1932011-06-15 23:02:42 +00001834 if (type->isBlockPointerType()) {
John McCalla59e4b72011-11-09 03:17:26 +00001835 ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
John McCallf85e1932011-06-15 23:02:42 +00001836 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1837
1838 // Otherwise, we transfer ownership of the retain from the stack
1839 // to the heap.
1840 } else {
1841 ARCStrongByrefHelpers byrefInfo(emission.Alignment);
1842 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
1843 }
1844 }
1845 llvm_unreachable("fell out of lifetime switch!");
1846 }
1847
John McCallf0c11f72011-03-31 08:03:29 +00001848 BlockFieldFlags flags;
1849 if (type->isBlockPointerType()) {
1850 flags |= BLOCK_FIELD_IS_BLOCK;
1851 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1852 type->isObjCObjectPointerType()) {
1853 flags |= BLOCK_FIELD_IS_OBJECT;
1854 } else {
1855 return 0;
1856 }
1857
1858 if (type.isObjCGCWeak())
1859 flags |= BLOCK_FIELD_IS_WEAK;
1860
1861 ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
1862 return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
Mike Stump45031c02009-03-06 02:29:21 +00001863}
1864
John McCall5af02db2011-03-31 01:59:53 +00001865unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
1866 assert(ByRefValueInfo.count(VD) && "Did not find value!");
1867
1868 return ByRefValueInfo.find(VD)->second.second;
1869}
1870
1871llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
1872 const VarDecl *V) {
1873 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
1874 Loc = Builder.CreateLoad(Loc);
1875 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
1876 V->getNameAsString());
1877 return Loc;
1878}
1879
1880/// BuildByRefType - This routine changes a __block variable declared as T x
1881/// into:
1882///
1883/// struct {
1884/// void *__isa;
1885/// void *__forwarding;
1886/// int32_t __flags;
1887/// int32_t __size;
1888/// void *__copy_helper; // only if needed
1889/// void *__destroy_helper; // only if needed
1890/// char padding[X]; // only if needed
1891/// T x;
1892/// } x
1893///
Chris Lattner2acc6e32011-07-18 04:24:23 +00001894llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
1895 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall5af02db2011-03-31 01:59:53 +00001896 if (Info.first)
1897 return Info.first;
1898
1899 QualType Ty = D->getType();
1900
Chris Lattner5f9e2722011-07-23 10:55:15 +00001901 SmallVector<llvm::Type *, 8> types;
John McCall5af02db2011-03-31 01:59:53 +00001902
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001903 llvm::StructType *ByRefType =
Chris Lattnerc1c20112011-08-12 17:43:31 +00001904 llvm::StructType::create(getLLVMContext(),
1905 "struct.__block_byref_" + D->getNameAsString());
John McCall5af02db2011-03-31 01:59:53 +00001906
1907 // void *__isa;
John McCall0774cb82011-05-15 01:53:33 +00001908 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001909
1910 // void *__forwarding;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001911 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall5af02db2011-03-31 01:59:53 +00001912
1913 // int32_t __flags;
John McCall0774cb82011-05-15 01:53:33 +00001914 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001915
1916 // int32_t __size;
John McCall0774cb82011-05-15 01:53:33 +00001917 types.push_back(Int32Ty);
John McCall5af02db2011-03-31 01:59:53 +00001918
David Chisnall9595dae2012-04-04 13:07:13 +00001919 bool HasCopyAndDispose =
1920 (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D);
John McCall5af02db2011-03-31 01:59:53 +00001921 if (HasCopyAndDispose) {
1922 /// void *__copy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001923 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001924
1925 /// void *__destroy_helper;
John McCall0774cb82011-05-15 01:53:33 +00001926 types.push_back(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001927 }
1928
1929 bool Packed = false;
1930 CharUnits Align = getContext().getDeclAlign(D);
1931 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
1932 // We have to insert padding.
1933
1934 // The struct above has 2 32-bit integers.
1935 unsigned CurrentOffsetInBytes = 4 * 2;
1936
1937 // And either 2 or 4 pointers.
1938 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
Micah Villmow25a6a842012-10-08 16:25:52 +00001939 CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall5af02db2011-03-31 01:59:53 +00001940
1941 // Align the offset.
1942 unsigned AlignedOffsetInBytes =
1943 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
1944
1945 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
1946 if (NumPaddingBytes > 0) {
Chris Lattner8b418682012-02-07 00:39:47 +00001947 llvm::Type *Ty = Int8Ty;
John McCall5af02db2011-03-31 01:59:53 +00001948 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall0774cb82011-05-15 01:53:33 +00001949 // the maximal stack alignment and the alignment of malloc on the system.
John McCall5af02db2011-03-31 01:59:53 +00001950 if (NumPaddingBytes > 1)
1951 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
1952
John McCall0774cb82011-05-15 01:53:33 +00001953 types.push_back(Ty);
John McCall5af02db2011-03-31 01:59:53 +00001954
1955 // We want a packed struct.
1956 Packed = true;
1957 }
1958 }
1959
1960 // T x;
John McCall0774cb82011-05-15 01:53:33 +00001961 types.push_back(ConvertTypeForMem(Ty));
John McCall5af02db2011-03-31 01:59:53 +00001962
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001963 ByRefType->setBody(types, Packed);
John McCall5af02db2011-03-31 01:59:53 +00001964
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001965 Info.first = ByRefType;
John McCall5af02db2011-03-31 01:59:53 +00001966
John McCall0774cb82011-05-15 01:53:33 +00001967 Info.second = types.size() - 1;
John McCall5af02db2011-03-31 01:59:53 +00001968
1969 return Info.first;
1970}
1971
1972/// Initialize the structural components of a __block variable, i.e.
1973/// everything but the actual object.
1974void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf0c11f72011-03-31 08:03:29 +00001975 // Find the address of the local.
1976 llvm::Value *addr = emission.Address;
John McCall5af02db2011-03-31 01:59:53 +00001977
John McCallf0c11f72011-03-31 08:03:29 +00001978 // That's an alloca of the byref structure type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001979 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf0c11f72011-03-31 08:03:29 +00001980 cast<llvm::PointerType>(addr->getType())->getElementType());
1981
1982 // Build the byref helpers if necessary. This is null if we don't need any.
1983 CodeGenModule::ByrefHelpers *helpers =
1984 buildByrefHelpers(*byrefType, emission);
John McCall5af02db2011-03-31 01:59:53 +00001985
1986 const VarDecl &D = *emission.Variable;
1987 QualType type = D.getType();
1988
John McCallf0c11f72011-03-31 08:03:29 +00001989 llvm::Value *V;
John McCall5af02db2011-03-31 01:59:53 +00001990
1991 // Initialize the 'isa', which is just 0 or 1.
1992 int isa = 0;
John McCallf0c11f72011-03-31 08:03:29 +00001993 if (type.isObjCGCWeak())
John McCall5af02db2011-03-31 01:59:53 +00001994 isa = 1;
1995 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
1996 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
1997
1998 // Store the address of the variable into its own forwarding pointer.
1999 Builder.CreateStore(addr,
2000 Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
2001
2002 // Blocks ABI:
2003 // c) the flags field is set to either 0 if no helper functions are
2004 // needed or BLOCK_HAS_COPY_DISPOSE if they are,
2005 BlockFlags flags;
John McCallf0c11f72011-03-31 08:03:29 +00002006 if (helpers) flags |= BLOCK_HAS_COPY_DISPOSE;
John McCall5af02db2011-03-31 01:59:53 +00002007 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2008 Builder.CreateStructGEP(addr, 2, "byref.flags"));
2009
John McCallf0c11f72011-03-31 08:03:29 +00002010 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2011 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall5af02db2011-03-31 01:59:53 +00002012 Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
2013
John McCallf0c11f72011-03-31 08:03:29 +00002014 if (helpers) {
John McCall5af02db2011-03-31 01:59:53 +00002015 llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
John McCallf0c11f72011-03-31 08:03:29 +00002016 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002017
2018 llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
John McCallf0c11f72011-03-31 08:03:29 +00002019 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall5af02db2011-03-31 01:59:53 +00002020 }
2021}
2022
John McCalld16c2cf2011-02-08 08:22:06 +00002023void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar673431a2010-07-16 00:00:15 +00002024 llvm::Value *F = CGM.getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00002025 llvm::Value *N;
John McCalld16c2cf2011-02-08 08:22:06 +00002026 V = Builder.CreateBitCast(V, Int8PtrTy);
2027 N = llvm::ConstantInt::get(Int32Ty, flags.getBitMask());
Mike Stump797b6322009-03-05 01:23:13 +00002028 Builder.CreateCall2(F, V, N);
2029}
John McCall5af02db2011-03-31 01:59:53 +00002030
2031namespace {
2032 struct CallBlockRelease : EHScopeStack::Cleanup {
2033 llvm::Value *Addr;
2034 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2035
John McCallad346f42011-07-12 20:27:29 +00002036 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002037 // Should we be passing FIELD_IS_WEAK here?
John McCall5af02db2011-03-31 01:59:53 +00002038 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2039 }
2040 };
2041}
2042
2043/// Enter a cleanup to destroy a __block variable. Note that this
2044/// cleanup should be a no-op if the variable hasn't left the stack
2045/// yet; if a cleanup is required for the variable itself, that needs
2046/// to be done externally.
2047void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2048 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00002049 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall5af02db2011-03-31 01:59:53 +00002050 return;
2051
2052 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2053}
John McCall13db5cf2011-09-09 20:41:01 +00002054
2055/// Adjust the declaration of something from the blocks API.
2056static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2057 llvm::Constant *C) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002058 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall13db5cf2011-09-09 20:41:01 +00002059
2060 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
2061 if (GV->isDeclaration() &&
2062 GV->getLinkage() == llvm::GlobalValue::ExternalLinkage)
2063 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2064}
2065
2066llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2067 if (BlockObjectDispose)
2068 return BlockObjectDispose;
2069
2070 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2071 llvm::FunctionType *fty
2072 = llvm::FunctionType::get(VoidTy, args, false);
2073 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2074 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2075 return BlockObjectDispose;
2076}
2077
2078llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2079 if (BlockObjectAssign)
2080 return BlockObjectAssign;
2081
2082 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2083 llvm::FunctionType *fty
2084 = llvm::FunctionType::get(VoidTy, args, false);
2085 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2086 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2087 return BlockObjectAssign;
2088}
2089
2090llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2091 if (NSConcreteGlobalBlock)
2092 return NSConcreteGlobalBlock;
2093
2094 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
2095 Int8PtrTy->getPointerTo(), 0);
2096 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2097 return NSConcreteGlobalBlock;
2098}
2099
2100llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2101 if (NSConcreteStackBlock)
2102 return NSConcreteStackBlock;
2103
2104 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
2105 Int8PtrTy->getPointerTo(), 0);
2106 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2107 return NSConcreteStackBlock;
2108}