blob: adc9de1792a1f2430bb87a0a3c6772b38da02ce2 [file] [log] [blame]
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump692c6e32009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000024#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000025#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000026
Anders Carlsson2437cbf2009-02-12 00:39:25 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall08ef4662011-11-10 08:15:53 +000030CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000032 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
Craig Topper8a13c412014-05-21 05:09:00 +000033 StructureType(nullptr), Block(block),
34 DominatingIP(nullptr) {
35
John McCall08ef4662011-11-10 08:15:53 +000036 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000040}
41
John McCallf9b056b2011-03-31 08:03:29 +000042// Anchor the vtable to this translation unit.
43CodeGenModule::ByrefHelpers::~ByrefHelpers() {}
44
John McCall351762c2011-02-07 10:33:21 +000045/// Build the given block as a global block.
46static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000049
John McCall351762c2011-02-07 10:33:21 +000050/// Build the helper function to copy a block.
51static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54}
55
Alp Tokerf6a24ce2013-12-05 16:25:25 +000056/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000057static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60}
61
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000062/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63/// buildBlockDescriptor is accessed from 5th field of the Block_literal
64/// meta-data and contains stationary information about the block literal.
65/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000066/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000067/// struct Block_descriptor {
68/// unsigned long reserved;
69/// unsigned long size; // size of Block_literal metadata in bytes.
70/// void *copy_func_helper_decl; // optional copy helper.
71/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000072/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000073/// void *block_layout_info; // encoding of captured block variables.
74/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000075/// \endcode
John McCall351762c2011-02-07 10:33:21 +000076static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
79
Chris Lattner2192fe52011-07-18 04:24:23 +000080 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000081 llvm::Type *i8p = NULL;
82 if (CGM.getLangOpts().OpenCL)
83 i8p =
84 llvm::Type::getInt8PtrTy(
85 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
86 else
87 i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +000088
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 SmallVector<llvm::Constant*, 6> elements;
Mike Stump85284ba2009-02-13 16:19:19 +000090
91 // reserved
John McCall351762c2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000095 // FIXME: What is the right way to say this doesn't fit? We should give
96 // a user diagnostic in that case. Better fix would be to change the
97 // API to size_t.
John McCall351762c2011-02-07 10:33:21 +000098 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
Mike Stump85284ba2009-02-13 16:19:19 +0000100
John McCall351762c2011-02-07 10:33:21 +0000101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000103 // copy_func_helper_decl
John McCall351762c2011-02-07 10:33:21 +0000104 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000105
106 // destroy_func_decl
John McCall351762c2011-02-07 10:33:21 +0000107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000108 }
109
John McCall351762c2011-02-07 10:33:21 +0000110 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111 std::string typeAtEncoding =
112 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113 elements.push_back(llvm::ConstantExpr::getBitCast(
114 CGM.GetAddrOfConstantCString(typeAtEncoding), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000115
John McCall351762c2011-02-07 10:33:21 +0000116 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000117 if (C.getLangOpts().ObjC1) {
118 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120 else
121 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122 }
John McCall351762c2011-02-07 10:33:21 +0000123 else
124 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000125
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
John McCall351762c2011-02-07 10:33:21 +0000128 llvm::GlobalVariable *global =
129 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130 llvm::GlobalValue::InternalLinkage,
131 init, "__block_descriptor_tmp");
Mike Stump85284ba2009-02-13 16:19:19 +0000132
John McCall351762c2011-02-07 10:33:21 +0000133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000134}
135
John McCall351762c2011-02-07 10:33:21 +0000136/*
137 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000138
John McCall351762c2011-02-07 10:33:21 +0000139 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140 struct Block_literal {
141 /// Initialized to one of:
142 /// extern void *_NSConcreteStackBlock[];
143 /// extern void *_NSConcreteGlobalBlock[];
144 ///
145 /// In theory, we could start one off malloc'ed by setting
146 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147 /// this isa:
148 /// extern void *_NSConcreteMallocBlock[];
149 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000150
John McCall351762c2011-02-07 10:33:21 +0000151 /// These are the flags (with corresponding bit number) that the
152 /// compiler is actually supposed to know about.
153 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154 /// descriptor provides copy and dispose helper functions
155 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156 /// object with a nontrivial destructor or copy constructor
157 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158 /// as global memory
159 /// 29. BLOCK_USE_STRET - indicates that the block function
160 /// uses stret, which objc_msgSend needs to know about
161 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162 /// @encoded signature string
163 /// And we're not supposed to manipulate these:
164 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165 /// to malloc'ed memory
166 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167 /// to GC-allocated memory
168 /// Additionally, the bottom 16 bits are a reference count which
169 /// should be zero on the stack.
170 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000171
John McCall351762c2011-02-07 10:33:21 +0000172 /// Reserved; should be zero-initialized.
173 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000174
John McCall351762c2011-02-07 10:33:21 +0000175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Captured values follow.
182 _CapturesTypes captures...;
183 };
184 */
David Chisnall950a9512009-11-17 19:33:30 +0000185
John McCall351762c2011-02-07 10:33:21 +0000186/// The number of fields in a block header.
187const unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000188
John McCall351762c2011-02-07 10:33:21 +0000189namespace {
190 /// A chunk of data that we actually have to capture in the block.
191 struct BlockLayoutChunk {
192 CharUnits Alignment;
193 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000194 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000195 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000196 llvm::Type *Type;
Mike Stump85284ba2009-02-13 16:19:19 +0000197
John McCall351762c2011-02-07 10:33:21 +0000198 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000199 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000200 const BlockDecl::Capture *capture,
Jay Foad7c57be32011-07-11 09:56:20 +0000201 llvm::Type *type)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 /// Tell the block info that this chunk has the given field index.
206 void setIndex(CGBlockInfo &info, unsigned index) {
207 if (!Capture)
208 info.CXXThisIndex = index;
John McCall87fe5d52010-05-20 01:18:31 +0000209 else
John McCall351762c2011-02-07 10:33:21 +0000210 info.Captures[Capture->getVariable()]
211 = CGBlockInfo::Capture::makeIndex(index);
John McCall87fe5d52010-05-20 01:18:31 +0000212 }
John McCall351762c2011-02-07 10:33:21 +0000213 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000214
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000215 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
216 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000217 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000218 CharUnits LeftValue, RightValue;
219 bool LeftByref = left.Capture ? left.Capture->isByRef() : false;
220 bool RightByref = right.Capture ? right.Capture->isByRef() : false;
221
222 if (left.Lifetime == Qualifiers::OCL_Strong &&
223 left.Alignment >= right.Alignment)
224 LeftValue = CharUnits::fromQuantity(64);
225 else if (LeftByref && left.Alignment >= right.Alignment)
226 LeftValue = CharUnits::fromQuantity(32);
227 else if (left.Lifetime == Qualifiers::OCL_Weak &&
228 left.Alignment >= right.Alignment)
229 LeftValue = CharUnits::fromQuantity(16);
230 else
231 LeftValue = left.Alignment;
232 if (right.Lifetime == Qualifiers::OCL_Strong &&
233 right.Alignment >= left.Alignment)
234 RightValue = CharUnits::fromQuantity(64);
235 else if (RightByref && right.Alignment >= left.Alignment)
236 RightValue = CharUnits::fromQuantity(32);
237 else if (right.Lifetime == Qualifiers::OCL_Weak &&
238 right.Alignment >= left.Alignment)
239 RightValue = CharUnits::fromQuantity(16);
240 else
241 RightValue = right.Alignment;
242
243 return LeftValue > RightValue;
John McCall351762c2011-02-07 10:33:21 +0000244 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000245}
John McCall351762c2011-02-07 10:33:21 +0000246
John McCallb0a3ecb2011-02-08 03:07:00 +0000247/// Determines if the given type is safe for constant capture in C++.
248static bool isSafeForCXXConstantCapture(QualType type) {
249 const RecordType *recordType =
250 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
251
252 // Only records can be unsafe.
253 if (!recordType) return true;
254
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000255 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000256
257 // Maintain semantics for classes with non-trivial dtors or copy ctors.
258 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000259 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000260
261 // Otherwise, we just have to make sure there aren't any mutable
262 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000263 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000264}
265
John McCall351762c2011-02-07 10:33:21 +0000266/// It is illegal to modify a const object after initialization.
267/// Therefore, if a const object has a constant initializer, we don't
268/// actually need to keep storage for it in the block; we'll just
269/// rematerialize it at the start of the block function. This is
270/// acceptable because we make no promises about address stability of
271/// captured variables.
272static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000273 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000274 const VarDecl *var) {
275 QualType type = var->getType();
276
277 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000278 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000279
John McCallb0a3ecb2011-02-08 03:07:00 +0000280 // Furthermore, in C++ we have to worry about mutable fields:
281 // C++ [dcl.type.cv]p4:
282 // Except that any class member declared mutable can be
283 // modified, any attempt to modify a const object during its
284 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000285 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000286 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000287
288 // If the variable doesn't have any initializer (shouldn't this be
289 // invalid?), it's not clear what we should do. Maybe capture as
290 // zero?
291 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000292 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000293
Richard Smithdafff942012-01-14 04:30:29 +0000294 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000295}
296
297/// Get the low bit of a nonzero character count. This is the
298/// alignment of the nth byte if the 0th byte is universally aligned.
299static CharUnits getLowBit(CharUnits v) {
300 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
301}
302
303static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall351762c2011-02-07 10:33:21 +0000305 ASTContext &C = CGM.getContext();
306
307 // The header is basically a 'struct { void *; int; int; void *; void *; }'.
308 CharUnits ptrSize, ptrAlign, intSize, intAlign;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000309 std::tie(ptrSize, ptrAlign) = C.getTypeInfoInChars(C.VoidPtrTy);
310 std::tie(intSize, intAlign) = C.getTypeInfoInChars(C.IntTy);
John McCall351762c2011-02-07 10:33:21 +0000311
312 // Are there crazy embedded platforms where this isn't true?
313 assert(intSize <= ptrSize && "layout assumptions horribly violated");
314
315 CharUnits headerSize = ptrSize;
316 if (2 * intSize < ptrAlign) headerSize += ptrSize;
317 else headerSize += 2 * intSize;
318 headerSize += 2 * ptrSize;
319
320 info.BlockAlign = ptrAlign;
321 info.BlockSize = headerSize;
322
323 assert(elementTypes.empty());
Jay Foad7c57be32011-07-11 09:56:20 +0000324 llvm::Type *i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
325 llvm::Type *intTy = CGM.getTypes().ConvertType(C.IntTy);
John McCall351762c2011-02-07 10:33:21 +0000326 elementTypes.push_back(i8p);
327 elementTypes.push_back(intTy);
328 elementTypes.push_back(intTy);
329 elementTypes.push_back(i8p);
330 elementTypes.push_back(CGM.getBlockDescriptorType());
331
332 assert(elementTypes.size() == BlockHeaderSize);
333}
334
335/// Compute the layout of the given block. Attempts to lay the block
336/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000337static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
338 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000339 ASTContext &C = CGM.getContext();
340 const BlockDecl *block = info.getBlockDecl();
341
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000343 initializeForBlockHeader(CGM, info, elementTypes);
344
345 if (!block->hasCaptures()) {
346 info.StructureType =
347 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
348 info.CanBeGlobal = true;
349 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000350 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000351 else if (C.getLangOpts().ObjC1 &&
352 CGM.getLangOpts().getGC() == LangOptions::NonGC)
353 info.HasCapturedVariableLayout = true;
354
John McCall351762c2011-02-07 10:33:21 +0000355 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000356 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000357 layout.reserve(block->capturesCXXThis() +
358 (block->capture_end() - block->capture_begin()));
359
360 CharUnits maxFieldAlign;
361
362 // First, 'this'.
363 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000364 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
365 "Can't capture 'this' outside a method");
366 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000367
Jay Foad7c57be32011-07-11 09:56:20 +0000368 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000369 std::pair<CharUnits,CharUnits> tinfo
370 = CGM.getContext().getTypeInfoInChars(thisType);
371 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
372
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000373 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
374 Qualifiers::OCL_None,
Craig Topper8a13c412014-05-21 05:09:00 +0000375 nullptr, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000376 }
377
378 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000379 for (const auto &CI : block->captures()) {
380 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000381
Aaron Ballman9371dd22014-03-14 18:34:04 +0000382 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000383 // We have to copy/dispose of the __block reference.
384 info.NeedsCopyDispose = true;
385
John McCall351762c2011-02-07 10:33:21 +0000386 // Just use void* instead of a pointer to the byref type.
387 QualType byRefPtrTy = C.VoidPtrTy;
388
Jay Foad7c57be32011-07-11 09:56:20 +0000389 llvm::Type *llvmType = CGM.getTypes().ConvertType(byRefPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000390 std::pair<CharUnits,CharUnits> tinfo
391 = CGM.getContext().getTypeInfoInChars(byRefPtrTy);
392 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
393
394 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
Aaron Ballman9371dd22014-03-14 18:34:04 +0000395 Qualifiers::OCL_None, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000396 continue;
397 }
398
399 // Otherwise, build a layout chunk with the size and alignment of
400 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000401 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000402 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
403 continue;
404 }
405
John McCall31168b02011-06-15 23:02:42 +0000406 // If we have a lifetime qualifier, honor it for capture purposes.
407 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000408 Qualifiers::ObjCLifetime lifetime =
409 variable->getType().getObjCLifetime();
410 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000411 switch (lifetime) {
412 case Qualifiers::OCL_None: llvm_unreachable("impossible");
413 case Qualifiers::OCL_ExplicitNone:
414 case Qualifiers::OCL_Autoreleasing:
415 break;
John McCall351762c2011-02-07 10:33:21 +0000416
John McCall31168b02011-06-15 23:02:42 +0000417 case Qualifiers::OCL_Strong:
418 case Qualifiers::OCL_Weak:
419 info.NeedsCopyDispose = true;
420 }
421
422 // Block pointers require copy/dispose. So do Objective-C pointers.
423 } else if (variable->getType()->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +0000424 info.NeedsCopyDispose = true;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000425 // used for mrr below.
426 lifetime = Qualifiers::OCL_Strong;
John McCall351762c2011-02-07 10:33:21 +0000427
428 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000429 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000430 info.NeedsCopyDispose = true;
431 info.HasCXXObject = true;
432
433 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000434 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000435 if (const CXXRecordDecl *record =
436 variable->getType()->getAsCXXRecordDecl()) {
437 if (!record->hasTrivialDestructor()) {
438 info.HasCXXObject = true;
439 info.NeedsCopyDispose = true;
440 }
441 }
442 }
443
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000444 QualType VT = variable->getType();
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000445 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000446 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000447
John McCall351762c2011-02-07 10:33:21 +0000448 maxFieldAlign = std::max(maxFieldAlign, align);
449
Jay Foad7c57be32011-07-11 09:56:20 +0000450 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000451 CGM.getTypes().ConvertTypeForMem(VT);
452
Aaron Ballman9371dd22014-03-14 18:34:04 +0000453 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000454 }
455
456 // If that was everything, we're done here.
457 if (layout.empty()) {
458 info.StructureType =
459 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
460 info.CanBeGlobal = true;
461 return;
462 }
463
464 // Sort the layout by alignment. We have to use a stable sort here
465 // to get reproducible results. There should probably be an
466 // llvm::array_pod_stable_sort.
467 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000468
469 // Needed for blocks layout info.
470 info.BlockHeaderForcedGapOffset = info.BlockSize;
471 info.BlockHeaderForcedGapSize = CharUnits::Zero();
472
John McCall351762c2011-02-07 10:33:21 +0000473 CharUnits &blockSize = info.BlockSize;
474 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
475
476 // Assuming that the first byte in the header is maximally aligned,
477 // get the alignment of the first byte following the header.
478 CharUnits endAlign = getLowBit(blockSize);
479
480 // If the end of the header isn't satisfactorily aligned for the
481 // maximum thing, look for things that are okay with the header-end
482 // alignment, and keep appending them until we get something that's
483 // aligned right. This algorithm is only guaranteed optimal if
484 // that condition is satisfied at some point; otherwise we can get
485 // things like:
486 // header // next byte has alignment 4
487 // something_with_size_5; // next byte has alignment 1
488 // something_with_alignment_8;
489 // which has 7 bytes of padding, as opposed to the naive solution
490 // which might have less (?).
491 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000493 li = layout.begin() + 1, le = layout.end();
494
495 // Look for something that the header end is already
496 // satisfactorily aligned for.
497 for (; li != le && endAlign < li->Alignment; ++li)
498 ;
499
500 // If we found something that's naturally aligned for the end of
501 // the header, keep adding things...
502 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000503 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000504 for (; li != le; ++li) {
505 assert(endAlign >= li->Alignment);
506
507 li->setIndex(info, elementTypes.size());
508 elementTypes.push_back(li->Type);
509 blockSize += li->Size;
510 endAlign = getLowBit(blockSize);
511
512 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000513 if (endAlign >= maxFieldAlign) {
514 if (li == first) {
515 // No user field was appended. So, a gap was added.
516 // Save total gap size for use in block layout bit map.
517 info.BlockHeaderForcedGapSize = li->Size;
518 }
John McCall351762c2011-02-07 10:33:21 +0000519 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000520 }
John McCall351762c2011-02-07 10:33:21 +0000521 }
John McCall351762c2011-02-07 10:33:21 +0000522 // Don't re-append everything we just appended.
523 layout.erase(first, li);
524 }
525 }
526
John McCallac0350a2012-04-26 21:14:42 +0000527 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000528
John McCall351762c2011-02-07 10:33:21 +0000529 // At this point, we just have to add padding if the end align still
530 // isn't aligned right.
531 if (endAlign < maxFieldAlign) {
John McCallac0350a2012-04-26 21:14:42 +0000532 CharUnits newBlockSize = blockSize.RoundUpToAlignment(maxFieldAlign);
533 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000534
John McCalle3dc1702011-02-15 09:22:45 +0000535 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
536 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000537 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000538 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000539 }
540
John McCall1db0a2f2012-05-01 20:28:00 +0000541 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000542 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000543 // Slam everything else on now. This works because they have
544 // strictly decreasing alignment and we expect that size is always a
545 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000546 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000547 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000548 if (endAlign < li->Alignment) {
549 // size may not be multiple of alignment. This can only happen with
550 // an over-aligned variable. We will be adding a padding field to
551 // make the size be multiple of alignment.
552 CharUnits padding = li->Alignment - endAlign;
553 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
554 padding.getQuantity()));
555 blockSize += padding;
556 endAlign = getLowBit(blockSize);
557 }
John McCall351762c2011-02-07 10:33:21 +0000558 assert(endAlign >= li->Alignment);
559 li->setIndex(info, elementTypes.size());
560 elementTypes.push_back(li->Type);
561 blockSize += li->Size;
562 endAlign = getLowBit(blockSize);
563 }
564
565 info.StructureType =
566 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
567}
568
John McCall08ef4662011-11-10 08:15:53 +0000569/// Enter the scope of a block. This should be run at the entrance to
570/// a full-expression so that the block's cleanups are pushed at the
571/// right place in the stack.
572static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000573 assert(CGF.HaveInsertPoint());
574
John McCall08ef4662011-11-10 08:15:53 +0000575 // Allocate the block info and place it at the head of the list.
576 CGBlockInfo &blockInfo =
577 *new CGBlockInfo(block, CGF.CurFn->getName());
578 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
579 CGF.FirstBlockInfo = &blockInfo;
580
581 // Compute information about the layout, etc., of this block,
582 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000583 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000584
585 // Nothing else to do if it can be global.
586 if (blockInfo.CanBeGlobal) return;
587
588 // Make the allocation for the block.
589 blockInfo.Address =
590 CGF.CreateTempAlloca(blockInfo.StructureType, "block");
591 blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
592
593 // If there are cleanups to emit, enter them (but inactive).
594 if (!blockInfo.NeedsCopyDispose) return;
595
596 // Walk through the captures (in order) and find the ones not
597 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000598 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000599 // Ignore __block captures; there's nothing special in the
600 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000601 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000602
603 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000604 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000605 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
606 if (capture.isConstant()) continue;
607
608 // Ignore objects that aren't destructed.
609 QualType::DestructionKind dtorKind =
610 variable->getType().isDestructedType();
611 if (dtorKind == QualType::DK_none) continue;
612
613 CodeGenFunction::Destroyer *destroyer;
614
615 // Block captures count as local values and have imprecise semantics.
616 // They also can't be arrays, so need to worry about that.
617 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000618 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000619 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000620 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000621 }
622
623 // GEP down to the address.
David Blaikie1ed728c2015-04-05 22:45:47 +0000624 llvm::Value *addr = CGF.Builder.CreateStructGEP(
625 blockInfo.StructureType, blockInfo.Address, capture.getIndex());
John McCall08ef4662011-11-10 08:15:53 +0000626
John McCallf4beacd2011-11-10 10:43:54 +0000627 // We can use that GEP as the dominating IP.
628 if (!blockInfo.DominatingIP)
629 blockInfo.DominatingIP = cast<llvm::Instruction>(addr);
630
John McCall08ef4662011-11-10 08:15:53 +0000631 CleanupKind cleanupKind = InactiveNormalCleanup;
632 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
633 if (useArrayEHCleanup)
634 cleanupKind = InactiveNormalAndEHCleanup;
635
636 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000637 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000638
639 // Remember where that cleanup was.
640 capture.setCleanup(CGF.EHStack.stable_begin());
641 }
642}
643
644/// Enter a full-expression with a non-trivial number of objects to
645/// clean up. This is in this file because, at the moment, the only
646/// kind of cleanup object is a BlockDecl*.
647void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
648 assert(E->getNumObjects() != 0);
649 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
650 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
651 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
652 enterBlockScope(*this, *i);
653 }
654}
655
656/// Find the layout for the given block in a linked list and remove it.
657static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
658 const BlockDecl *block) {
659 while (true) {
660 assert(head && *head);
661 CGBlockInfo *cur = *head;
662
663 // If this is the block we're looking for, splice it out of the list.
664 if (cur->getBlockDecl() == block) {
665 *head = cur->NextBlockInfo;
666 return cur;
667 }
668
669 head = &cur->NextBlockInfo;
670 }
671}
672
673/// Destroy a chain of block layouts.
674void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
675 assert(head && "destroying an empty chain");
676 do {
677 CGBlockInfo *cur = head;
678 head = cur->NextBlockInfo;
679 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000680 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000681}
682
John McCall351762c2011-02-07 10:33:21 +0000683/// Emit a block literal expression in the current function.
684llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000685 // If the block has no captures, we won't have a pre-computed
686 // layout for it.
687 if (!blockExpr->getBlockDecl()->hasCaptures()) {
688 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000689 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000690 blockInfo.BlockExpression = blockExpr;
691 return EmitBlockLiteral(blockInfo);
692 }
John McCall351762c2011-02-07 10:33:21 +0000693
John McCall08ef4662011-11-10 08:15:53 +0000694 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000695 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000696 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
697 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000698
John McCall08ef4662011-11-10 08:15:53 +0000699 blockInfo->BlockExpression = blockExpr;
700 return EmitBlockLiteral(*blockInfo);
701}
702
703llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
704 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000705 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000706 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000707 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000708 LocalDeclMap,
709 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000710 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000711
712 // If there is nothing to capture, we can emit this as a global block.
713 if (blockInfo.CanBeGlobal)
714 return buildGlobalBlock(CGM, blockInfo, blockFn);
715
716 // Otherwise, we have to emit this as a local block.
717
718 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000719 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000720
721 // Build the block descriptor.
722 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
723
David Blaikie1ed728c2015-04-05 22:45:47 +0000724 llvm::Type *blockTy = blockInfo.StructureType;
John McCall08ef4662011-11-10 08:15:53 +0000725 llvm::AllocaInst *blockAddr = blockInfo.Address;
726 assert(blockAddr && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000727
728 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000729 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000730 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000731 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
732 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000733 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000734
735 // Initialize the block literal.
David Blaikie2e804282015-04-05 22:47:07 +0000736 Builder.CreateStore(
737 isa, Builder.CreateStructGEP(blockTy, blockAddr, 0, "block.isa"));
738 Builder.CreateStore(
739 llvm::ConstantInt::get(IntTy, flags.getBitMask()),
740 Builder.CreateStructGEP(blockTy, blockAddr, 1, "block.flags"));
741 Builder.CreateStore(
742 llvm::ConstantInt::get(IntTy, 0),
743 Builder.CreateStructGEP(blockTy, blockAddr, 2, "block.reserved"));
744 Builder.CreateStore(
745 blockFn, Builder.CreateStructGEP(blockTy, blockAddr, 3, "block.invoke"));
David Blaikie1ed728c2015-04-05 22:45:47 +0000746 Builder.CreateStore(descriptor, Builder.CreateStructGEP(blockTy, blockAddr, 4,
John McCall351762c2011-02-07 10:33:21 +0000747 "block.descriptor"));
748
749 // Finally, capture all the values into the block.
750 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
751
752 // First, 'this'.
753 if (blockDecl->capturesCXXThis()) {
David Blaikie2e804282015-04-05 22:47:07 +0000754 llvm::Value *addr = Builder.CreateStructGEP(
755 blockTy, blockAddr, blockInfo.CXXThisIndex, "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000756 Builder.CreateStore(LoadCXXThis(), addr);
757 }
758
759 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000760 for (const auto &CI : blockDecl->captures()) {
761 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000762 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
763
764 // Ignore constant captures.
765 if (capture.isConstant()) continue;
766
767 QualType type = variable->getType();
John McCall4d14a902013-04-08 23:27:49 +0000768 CharUnits align = getContext().getDeclAlign(variable);
John McCall351762c2011-02-07 10:33:21 +0000769
770 // This will be a [[type]]*, except that a byref entry will just be
771 // an i8**.
David Blaikie2e804282015-04-05 22:47:07 +0000772 llvm::Value *blockField = Builder.CreateStructGEP(
773 blockTy, blockAddr, capture.getIndex(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000774
775 // Compute the address of the thing we're going to move into the
776 // block literal.
777 llvm::Value *src;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000778 if (BlockInfo && CI.isNested()) {
John McCall351762c2011-02-07 10:33:21 +0000779 // We need to use the capture from the enclosing block.
780 const CGBlockInfo::Capture &enclosingCapture =
781 BlockInfo->getCapture(variable);
782
783 // This is a [[type]]*, except that a byref entry wil just be an i8**.
David Blaikie1ed728c2015-04-05 22:45:47 +0000784 src = Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
John McCall351762c2011-02-07 10:33:21 +0000785 enclosingCapture.getIndex(),
786 "block.capture.addr");
Eli Friedman98b01ed2012-03-01 04:01:32 +0000787 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000788 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000789 // special; we'll simply emit it directly.
Craig Topper8a13c412014-05-21 05:09:00 +0000790 src = nullptr;
John McCall351762c2011-02-07 10:33:21 +0000791 } else {
John McCalla37c2fa2013-03-04 06:32:36 +0000792 // Just look it up in the locals map, which will give us back a
793 // [[type]]*. If that doesn't work, do the more elaborate DRE
794 // emission.
795 src = LocalDeclMap.lookup(variable);
796 if (!src) {
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000797 DeclRefExpr declRef(
798 const_cast<VarDecl *>(variable),
799 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
800 VK_LValue, SourceLocation());
John McCalla37c2fa2013-03-04 06:32:36 +0000801 src = EmitDeclRefLValue(&declRef).getAddress();
802 }
John McCall351762c2011-02-07 10:33:21 +0000803 }
804
805 // For byrefs, we just write the pointer to the byref struct into
806 // the block field. There's no need to chase the forwarding
807 // pointer at this point, since we're building something that will
808 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000809 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000810 // Get a void* that points to the byref struct.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000811 if (CI.isNested())
John McCall4d14a902013-04-08 23:27:49 +0000812 src = Builder.CreateAlignedLoad(src, align.getQuantity(),
813 "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000814 else
John McCalle3dc1702011-02-15 09:22:45 +0000815 src = Builder.CreateBitCast(src, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000816
John McCalle3dc1702011-02-15 09:22:45 +0000817 // Write that void* into the capture field.
John McCall4d14a902013-04-08 23:27:49 +0000818 Builder.CreateAlignedStore(src, blockField, align.getQuantity());
John McCall351762c2011-02-07 10:33:21 +0000819
820 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000821 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000822 if (blockDecl->isConversionFromLambda()) {
823 // If we have a lambda conversion, emit the expression
824 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000825 AggValueSlot Slot =
John McCall4d14a902013-04-08 23:27:49 +0000826 AggValueSlot::forAddr(blockField, align, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000827 AggValueSlot::IsDestructed,
828 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000829 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000830 EmitAggExpr(copyExpr, Slot);
831 } else {
832 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
833 }
John McCall351762c2011-02-07 10:33:21 +0000834
835 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000836 } else if (type->isReferenceType()) {
John McCall4d14a902013-04-08 23:27:49 +0000837 llvm::Value *ref =
838 Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
839 Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
840
841 // If this is an ARC __strong block-pointer variable, don't do a
842 // block copy.
843 //
844 // TODO: this can be generalized into the normal initialization logic:
845 // we should never need to do a block-copy when initializing a local
846 // variable, because the local variable's lifetime should be strictly
847 // contained within the stack block's.
848 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
849 type->isBlockPointerType()) {
850 // Load the block and do a simple retain.
851 LValue srcLV = MakeAddrLValue(src, type, align);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000852 llvm::Value *value = EmitLoadOfScalar(srcLV, SourceLocation());
John McCall4d14a902013-04-08 23:27:49 +0000853 value = EmitARCRetainNonBlock(value);
854
855 // Do a primitive store to the block field.
856 LValue destLV = MakeAddrLValue(blockField, type, align);
857 EmitStoreOfScalar(value, destLV, /*init*/ true);
John McCall351762c2011-02-07 10:33:21 +0000858
859 // Otherwise, fake up a POD copy into the block field.
860 } else {
John McCall31168b02011-06-15 23:02:42 +0000861 // Fake up a new variable so that EmitScalarInit doesn't think
862 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000863 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
864 SourceLocation(), /*name*/ nullptr,
865 type);
John McCall31168b02011-06-15 23:02:42 +0000866
John McCall93be3f72011-02-07 18:37:40 +0000867 // We use one of these or the other depending on whether the
868 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000869 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
870 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
871 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000872
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000873 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000874 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000875 // FIXME: Pass a specific location for the expr init so that the store is
876 // attributed to a reasonable location - otherwise it may be attributed to
877 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000878 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall4d14a902013-04-08 23:27:49 +0000879 MakeAddrLValue(blockField, type, align),
David Blaikie66e41972015-01-14 07:38:27 +0000880 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000881 }
882
John McCall08ef4662011-11-10 08:15:53 +0000883 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000884 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000885 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
886 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000887 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000888 }
John McCall351762c2011-02-07 10:33:21 +0000889 }
890
891 // Cast to the converted block-pointer type, which happens (somewhat
892 // unfortunately) to be a pointer to function type.
893 llvm::Value *result =
894 Builder.CreateBitCast(blockAddr,
895 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000896
John McCall351762c2011-02-07 10:33:21 +0000897 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000898}
899
900
Chris Lattnera5f58b02011-07-09 17:41:47 +0000901llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000902 if (BlockDescriptorType)
903 return BlockDescriptorType;
904
Chris Lattnera5f58b02011-07-09 17:41:47 +0000905 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000906 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000907
Mike Stump650c9322009-02-13 15:16:56 +0000908 // struct __block_descriptor {
909 // unsigned long reserved;
910 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000911 //
912 // // later, the following will be added
913 //
914 // struct {
915 // void (*copyHelper)();
916 // void (*copyHelper)();
917 // } helpers; // !!! optional
918 //
919 // const char *signature; // the block signature
920 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000921 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000922 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000923 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000924 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000925
John McCall351762c2011-02-07 10:33:21 +0000926 // Now form a pointer to that.
927 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stump650c9322009-02-13 15:16:56 +0000928 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000929}
930
Chris Lattnera5f58b02011-07-09 17:41:47 +0000931llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000932 if (GenericBlockLiteralType)
933 return GenericBlockLiteralType;
934
Chris Lattnera5f58b02011-07-09 17:41:47 +0000935 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000936
Mike Stump005c9a62009-02-13 15:25:34 +0000937 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000938 // void *__isa;
939 // int __flags;
940 // int __reserved;
941 // void (*__invoke)(void *);
942 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000943 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000944 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000945 llvm::StructType::create("struct.__block_literal_generic",
946 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000947 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000948
Mike Stump005c9a62009-02-13 15:25:34 +0000949 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000950}
951
Mike Stump5d2534ad2009-02-19 01:01:04 +0000952
Nick Lewycky2d84e842013-10-02 02:29:49 +0000953RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000954 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000955 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000956 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000957
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000958 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
959
960 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000961 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000962 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000963
964 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000965 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000966 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
967
968 // Get the function pointer from the literal.
David Blaikie1ed728c2015-04-05 22:45:47 +0000969 llvm::Value *FuncPtr = Builder.CreateStructGEP(
970 CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000971
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000972 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000973
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000974 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000975 CallArgList Args;
John McCall9dc0db22011-05-15 01:53:33 +0000976 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000977
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000978 QualType FnType = BPT->getPointeeType();
979
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000980 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +0000981 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +0000982
Anders Carlsson5f50c652009-04-07 22:10:22 +0000983 // Load the function.
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000984 llvm::Value *Func = Builder.CreateLoad(FuncPtr);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000985
John McCall85915252011-03-09 08:39:33 +0000986 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +0000987 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +0000988 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Anders Carlsson5f50c652009-04-07 22:10:22 +0000990 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +0000991 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Chris Lattner2192fe52011-07-18 04:24:23 +0000993 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000994 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000995
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000996 // And call the block.
Anders Carlssonbfb36712009-12-24 21:13:40 +0000997 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000998}
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000999
John McCall351762c2011-02-07 10:33:21 +00001000llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1001 bool isByRef) {
1002 assert(BlockInfo && "evaluating block ref without block information?");
1003 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001004
John McCall351762c2011-02-07 10:33:21 +00001005 // Handle constant captures.
1006 if (capture.isConstant()) return LocalDeclMap[variable];
John McCall87fe5d52010-05-20 01:18:31 +00001007
John McCall351762c2011-02-07 10:33:21 +00001008 llvm::Value *addr =
David Blaikie1ed728c2015-04-05 22:45:47 +00001009 Builder.CreateStructGEP(BlockInfo->StructureType, LoadBlockStruct(),
1010 capture.getIndex(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001011
John McCall351762c2011-02-07 10:33:21 +00001012 if (isByRef) {
1013 // addr should be a void** right now. Load, then cast the result
1014 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001015
John McCall351762c2011-02-07 10:33:21 +00001016 addr = Builder.CreateLoad(addr);
David Blaikie1ed728c2015-04-05 22:45:47 +00001017 auto *byrefType = BuildByRefType(variable);
1018 llvm::PointerType *byrefPointerType = llvm::PointerType::get(byrefType, 0);
John McCall351762c2011-02-07 10:33:21 +00001019 addr = Builder.CreateBitCast(addr, byrefPointerType,
1020 "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001021
John McCall351762c2011-02-07 10:33:21 +00001022 // Follow the forwarding pointer.
David Blaikie1ed728c2015-04-05 22:45:47 +00001023 addr = Builder.CreateStructGEP(byrefType, addr, 1, "byref.forwarding");
John McCall351762c2011-02-07 10:33:21 +00001024 addr = Builder.CreateLoad(addr, "byref.addr.forwarded");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001025
John McCall351762c2011-02-07 10:33:21 +00001026 // Cast back to byref* and GEP over to the actual object.
1027 addr = Builder.CreateBitCast(addr, byrefPointerType);
David Blaikie1ed728c2015-04-05 22:45:47 +00001028 addr = Builder.CreateStructGEP(byrefType, addr,
1029 getByRefValueLLVMField(variable).second,
John McCall351762c2011-02-07 10:33:21 +00001030 variable->getNameAsString());
John McCall87fe5d52010-05-20 01:18:31 +00001031 }
1032
Fariborz Jahanian10317ea2011-11-02 22:53:43 +00001033 if (variable->getType()->isReferenceType())
John McCall351762c2011-02-07 10:33:21 +00001034 addr = Builder.CreateLoad(addr, "ref.tmp");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001035
John McCall351762c2011-02-07 10:33:21 +00001036 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001037}
1038
Mike Stump2d5a2872009-02-14 22:16:35 +00001039llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001040CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001041 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001042 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1043 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001044
John McCall351762c2011-02-07 10:33:21 +00001045 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001046 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001047
John McCall351762c2011-02-07 10:33:21 +00001048 // Using that metadata, generate the actual block function.
1049 llvm::Constant *blockFn;
1050 {
1051 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001052 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1053 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001054 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001055 false);
John McCall351762c2011-02-07 10:33:21 +00001056 }
John McCalle3dc1702011-02-15 09:22:45 +00001057 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001058
John McCallad7c5c12011-02-08 08:22:06 +00001059 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001060}
1061
John McCall351762c2011-02-07 10:33:21 +00001062static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1063 const CGBlockInfo &blockInfo,
1064 llvm::Constant *blockFn) {
1065 assert(blockInfo.CanBeGlobal);
1066
1067 // Generate the constants for the block literal initializer.
1068 llvm::Constant *fields[BlockHeaderSize];
1069
1070 // isa
1071 fields[0] = CGM.getNSConcreteGlobalBlock();
1072
1073 // __flags
John McCall85915252011-03-09 08:39:33 +00001074 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1075 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1076
John McCalle3dc1702011-02-15 09:22:45 +00001077 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001078
1079 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001080 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001081
1082 // Function
1083 fields[3] = blockFn;
1084
1085 // Descriptor
1086 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1087
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001088 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001089
1090 llvm::GlobalVariable *literal =
1091 new llvm::GlobalVariable(CGM.getModule(),
1092 init->getType(),
1093 /*constant*/ true,
1094 llvm::GlobalVariable::InternalLinkage,
1095 init,
1096 "__block_literal_global");
1097 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1098
1099 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001100 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001101 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1102 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001103}
1104
Mike Stump4446dcf2009-03-05 08:32:30 +00001105llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001106CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1107 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001108 const DeclMapTy &ldm,
1109 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001110 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001111
Fariborz Jahanian63628032012-06-26 16:06:38 +00001112 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001113
1114 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001115
John McCall351762c2011-02-07 10:33:21 +00001116 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Mike Stump5469f292009-03-13 23:34:28 +00001118 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001119 // to be local to this function as well, in case they're directly
1120 // referenced in a block.
1121 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001122 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001123 if (var && !var->hasLocalStorage())
1124 LocalDeclMap[var] = i->second;
Mike Stump5469f292009-03-13 23:34:28 +00001125 }
1126
John McCall351762c2011-02-07 10:33:21 +00001127 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001128
John McCall351762c2011-02-07 10:33:21 +00001129 // Build the argument list.
1130 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001131
John McCall351762c2011-02-07 10:33:21 +00001132 // The first argument is the block pointer. Just take it as a void*
1133 // and cast it later.
1134 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001135 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001136
Richard Smith053f6c62014-05-16 23:01:30 +00001137 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001138 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001139 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001140
John McCall351762c2011-02-07 10:33:21 +00001141 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001142 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001143
John McCall351762c2011-02-07 10:33:21 +00001144 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001145 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
Reid Kleckner4982b822014-01-31 22:54:50 +00001146 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
Alp Toker314cc812014-01-25 16:55:45 +00001147 fnType->getReturnType(), args, fnType->getExtInfo(),
1148 fnType->isVariadic());
Tim Northovere77cc392014-03-29 13:28:05 +00001149 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001150 blockInfo.UsesStret = true;
1151
John McCalla729c622012-02-17 03:33:10 +00001152 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001153
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001154 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001155 llvm::Function *fn = llvm::Function::Create(
1156 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001157 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001158
John McCall351762c2011-02-07 10:33:21 +00001159 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001160 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001161 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001162 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001163
John McCall147d0212011-02-22 22:38:33 +00001164 // Okay. Undo some of what StartFunction did.
1165
1166 // Pull the 'self' reference out of the local decl map.
1167 llvm::Value *blockAddr = LocalDeclMap[&selfDecl];
1168 LocalDeclMap.erase(&selfDecl);
John McCall351762c2011-02-07 10:33:21 +00001169 BlockPointer = Builder.CreateBitCast(blockAddr,
1170 blockInfo.StructureType->getPointerTo(),
1171 "block");
Adrian Prantl0f6df002013-03-29 19:20:35 +00001172 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1173 // won't delete the dbg.declare intrinsics for captured variables.
1174 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1175 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1176 // Allocate a stack slot for it, so we can point the debugger to it
1177 llvm::AllocaInst *Alloca = CreateTempAlloca(BlockPointer->getType(),
1178 "block.addr");
1179 unsigned Align = getContext().getDeclAlign(&selfDecl).getQuantity();
1180 Alloca->setAlignment(Align);
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001181 // Set the DebugLocation to empty, so the store is recognized as a
1182 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001183 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl0f6df002013-03-29 19:20:35 +00001184 Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
1185 BlockPointerDbgLoc = Alloca;
1186 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001187
John McCall87fe5d52010-05-20 01:18:31 +00001188 // If we have a C++ 'this' reference, go ahead and force it into
1189 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001190 if (blockDecl->capturesCXXThis()) {
David Blaikie1ed728c2015-04-05 22:45:47 +00001191 llvm::Value *addr =
1192 Builder.CreateStructGEP(blockInfo.StructureType, BlockPointer,
1193 blockInfo.CXXThisIndex, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001194 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001195 }
1196
John McCall351762c2011-02-07 10:33:21 +00001197 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001198 for (const auto &CI : blockDecl->captures()) {
1199 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001200 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1201 if (!capture.isConstant()) continue;
1202
1203 unsigned align = getContext().getDeclAlign(variable).getQuantity();
1204
1205 llvm::AllocaInst *alloca =
1206 CreateMemTemp(variable->getType(), "block.captured-const");
1207 alloca->setAlignment(align);
1208
Adrian Prantl51936dd2013-03-14 17:53:33 +00001209 Builder.CreateAlignedStore(capture.getConstant(), alloca, align);
John McCall351762c2011-02-07 10:33:21 +00001210
1211 LocalDeclMap[variable] = alloca;
John McCall9d42f0f2010-05-21 04:11:14 +00001212 }
1213
John McCall113bee02012-03-10 09:33:50 +00001214 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001215 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1216 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1217 --entry_ptr;
1218
Eli Friedman2495ab02012-02-25 02:48:22 +00001219 if (IsLambdaConversionToBlock)
1220 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001221 else {
1222 PGO.assignRegionCounters(blockDecl, fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001223 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001224 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001225 }
Mike Stump017460a2009-10-01 22:29:41 +00001226
Mike Stump7d699112009-10-01 00:27:30 +00001227 // Remember where we were...
1228 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001229
Mike Stump7d699112009-10-01 00:27:30 +00001230 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001231 ++entry_ptr;
1232 Builder.SetInsertPoint(entry, entry_ptr);
1233
John McCall113bee02012-03-10 09:33:50 +00001234 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001235 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001236 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001237 for (const auto &CI : blockDecl->captures()) {
1238 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001239 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001240
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001241 if (CGM.getCodeGenOpts().getDebugInfo()
1242 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001243 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1244 if (capture.isConstant()) {
1245 DI->EmitDeclareOfAutoVariable(variable, LocalDeclMap[variable],
1246 Builder);
1247 continue;
1248 }
John McCall351762c2011-02-07 10:33:21 +00001249
Adrian Prantl0f6df002013-03-29 19:20:35 +00001250 DI->EmitDeclareOfBlockDeclRefVariable(variable, BlockPointerDbgLoc,
Adrian Prantl88eec392014-11-21 00:35:25 +00001251 Builder, blockInfo,
1252 entry_ptr == entry->end()
1253 ? nullptr : entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001254 }
Mike Stump2e722b92009-09-30 02:43:10 +00001255 }
Manman Renab08a9a2013-01-04 18:51:35 +00001256 // Recover location if it was changed in the above loop.
1257 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001258 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001259 }
John McCall351762c2011-02-07 10:33:21 +00001260
Mike Stump7d699112009-10-01 00:27:30 +00001261 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001262 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001263 Builder.ClearInsertionPoint();
1264 else
1265 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001266
John McCall351762c2011-02-07 10:33:21 +00001267 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001268
John McCall351762c2011-02-07 10:33:21 +00001269 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001270}
Mike Stump1db7d042009-02-28 09:07:16 +00001271
John McCall351762c2011-02-07 10:33:21 +00001272/*
1273 notes.push_back(HelperInfo());
1274 HelperInfo &note = notes.back();
1275 note.index = capture.getIndex();
1276 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1277 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001278
John McCall351762c2011-02-07 10:33:21 +00001279 if (ci->isByRef()) {
1280 note.flag = BLOCK_FIELD_IS_BYREF;
1281 if (type.isObjCGCWeak())
1282 note.flag |= BLOCK_FIELD_IS_WEAK;
1283 } else if (type->isBlockPointerType()) {
1284 note.flag = BLOCK_FIELD_IS_BLOCK;
1285 } else {
1286 note.flag = BLOCK_FIELD_IS_OBJECT;
1287 }
1288 */
Mike Stump1db7d042009-02-28 09:07:16 +00001289
Mike Stump4446dcf2009-03-05 08:32:30 +00001290
John McCallf593b102013-01-22 03:56:22 +00001291/// Generate the copy-helper function for a block closure object:
1292/// static void block_copy_helper(block_t *dst, block_t *src);
1293/// The runtime will have previously initialized 'dst' by doing a
1294/// bit-copy of 'src'.
1295///
1296/// Note that this copies an entire block closure object to the heap;
1297/// it should not be confused with a 'byref copy helper', which moves
1298/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001299llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001300CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001301 ASTContext &C = getContext();
1302
1303 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001304 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1305 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001306 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001307 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1308 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001309 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001310
Reid Kleckner4982b822014-01-31 22:54:50 +00001311 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1312 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001313
John McCall351762c2011-02-07 10:33:21 +00001314 // FIXME: it would be nice if these were mergeable with things with
1315 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001316 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001317
1318 llvm::Function *Fn =
1319 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001320 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001321
1322 IdentifierInfo *II
1323 = &CGM.getContext().Idents.get("__copy_helper_block_");
1324
John McCall351762c2011-02-07 10:33:21 +00001325 FunctionDecl *FD = FunctionDecl::Create(C,
1326 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001327 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001328 SourceLocation(), II, C.VoidTy,
1329 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001330 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001331 false);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001332 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001333 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001334 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001335 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001336 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001337
John McCalla738c252011-03-09 04:27:21 +00001338 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001339 src = Builder.CreateLoad(src);
1340 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001341
John McCalla738c252011-03-09 04:27:21 +00001342 llvm::Value *dst = GetAddrOfLocalVar(&dstDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001343 dst = Builder.CreateLoad(dst);
1344 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001345
John McCall351762c2011-02-07 10:33:21 +00001346 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001347
Aaron Ballman9371dd22014-03-14 18:34:04 +00001348 for (const auto &CI : blockDecl->captures()) {
1349 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001350 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001351
John McCall351762c2011-02-07 10:33:21 +00001352 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1353 if (capture.isConstant()) continue;
1354
Aaron Ballman9371dd22014-03-14 18:34:04 +00001355 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001356 BlockFieldFlags flags;
1357
John McCalle68b8f42012-10-17 02:28:37 +00001358 bool useARCWeakCopy = false;
1359 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001360
1361 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001362 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001363 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001364
Aaron Ballman9371dd22014-03-14 18:34:04 +00001365 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001366 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001367 if (type.isObjCGCWeak())
1368 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001369
John McCall31168b02011-06-15 23:02:42 +00001370 } else if (type->isObjCRetainableType()) {
1371 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001372 bool isBlockPointer = type->isBlockPointerType();
1373 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001374 flags = BLOCK_FIELD_IS_BLOCK;
1375
1376 // Special rules for ARC captures:
David Blaikiebbafb8a2012-03-11 07:00:24 +00001377 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001378 Qualifiers qs = type.getQualifiers();
1379
John McCalle68b8f42012-10-17 02:28:37 +00001380 // We need to register __weak direct captures with the runtime.
1381 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1382 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001383
John McCalle68b8f42012-10-17 02:28:37 +00001384 // We need to retain the copied value for __strong direct captures.
1385 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1386 // If it's a block pointer, we have to copy the block and
1387 // assign that to the destination pointer, so we might as
1388 // well use _Block_object_assign. Otherwise we can avoid that.
1389 if (!isBlockPointer)
1390 useARCStrongCopy = true;
1391
1392 // Otherwise the memcpy is fine.
1393 } else {
1394 continue;
1395 }
1396
1397 // Non-ARC captures of retainable pointers are strong and
1398 // therefore require a call to _Block_object_assign.
1399 } else {
1400 // fall through
John McCall31168b02011-06-15 23:02:42 +00001401 }
1402 } else {
1403 continue;
1404 }
John McCall351762c2011-02-07 10:33:21 +00001405
1406 unsigned index = capture.getIndex();
David Blaikie2e804282015-04-05 22:47:07 +00001407 llvm::Value *srcField =
1408 Builder.CreateStructGEP(blockInfo.StructureType, src, index);
1409 llvm::Value *dstField =
1410 Builder.CreateStructGEP(blockInfo.StructureType, dst, index);
John McCall351762c2011-02-07 10:33:21 +00001411
1412 // If there's an explicit copy expression, we do that.
1413 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001414 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001415 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001416 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001417 } else {
1418 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001419 if (useARCStrongCopy) {
1420 // At -O0, store null into the destination field (so that the
1421 // storeStrong doesn't over-release) and then call storeStrong.
1422 // This is a workaround to not having an initStrong call.
1423 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001424 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001425 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1426 Builder.CreateStore(null, dstField);
1427 EmitARCStoreStrongCall(dstField, srcValue, true);
1428
1429 // With optimization enabled, take advantage of the fact that
1430 // the blocks runtime guarantees a memcpy of the block data, and
1431 // just emit a retain of the src field.
1432 } else {
1433 EmitARCRetainNonBlock(srcValue);
1434
1435 // We don't need this anymore, so kill it. It's not quite
1436 // worth the annoyance to avoid creating it in the first place.
1437 cast<llvm::Instruction>(dstField)->eraseFromParent();
1438 }
1439 } else {
1440 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
1441 llvm::Value *dstAddr = Builder.CreateBitCast(dstField, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001442 llvm::Value *args[] = {
1443 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1444 };
1445
1446 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001447 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001448 const Expr *copyExpr =
1449 CGM.getContext().getBlockVarCopyInits(variable);
1450 if (copyExpr) {
1451 copyCanThrow = true; // FIXME: reuse the noexcept logic
1452 }
1453 }
1454
1455 if (copyCanThrow) {
1456 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1457 } else {
1458 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1459 }
John McCalle68b8f42012-10-17 02:28:37 +00001460 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001461 }
1462 }
1463
John McCallad7c5c12011-02-08 08:22:06 +00001464 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001465
John McCalle3dc1702011-02-15 09:22:45 +00001466 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001467}
1468
John McCallf593b102013-01-22 03:56:22 +00001469/// Generate the destroy-helper function for a block closure object:
1470/// static void block_destroy_helper(block_t *theBlock);
1471///
1472/// Note that this destroys a heap-allocated block closure object;
1473/// it should not be confused with a 'byref destroy helper', which
1474/// destroys the heap-allocated contents of an individual __block
1475/// variable.
John McCall351762c2011-02-07 10:33:21 +00001476llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001477CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001478 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001479
John McCall351762c2011-02-07 10:33:21 +00001480 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001481 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1482 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001483 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001484
Reid Kleckner4982b822014-01-31 22:54:50 +00001485 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1486 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001487
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001488 // FIXME: We'd like to put these into a mergable by content, with
1489 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001490 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001491
1492 llvm::Function *Fn =
1493 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001494 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001495
1496 IdentifierInfo *II
1497 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1498
John McCall351762c2011-02-07 10:33:21 +00001499 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001500 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001501 SourceLocation(), II, C.VoidTy,
1502 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001503 false, false);
Adrian Prantl49a78562013-07-24 20:34:39 +00001504 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001505 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001506 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001507 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001508
Chris Lattner2192fe52011-07-18 04:24:23 +00001509 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001510
John McCalla738c252011-03-09 04:27:21 +00001511 llvm::Value *src = GetAddrOfLocalVar(&srcDecl);
John McCallad7c5c12011-02-08 08:22:06 +00001512 src = Builder.CreateLoad(src);
1513 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001514
John McCall351762c2011-02-07 10:33:21 +00001515 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1516
John McCallad7c5c12011-02-08 08:22:06 +00001517 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001518
Aaron Ballman9371dd22014-03-14 18:34:04 +00001519 for (const auto &CI : blockDecl->captures()) {
1520 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001521 QualType type = variable->getType();
1522
1523 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1524 if (capture.isConstant()) continue;
1525
John McCallad7c5c12011-02-08 08:22:06 +00001526 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001527 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001528
John McCalle68b8f42012-10-17 02:28:37 +00001529 bool useARCWeakDestroy = false;
1530 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001531
Aaron Ballman9371dd22014-03-14 18:34:04 +00001532 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001533 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001534 if (type.isObjCGCWeak())
1535 flags |= BLOCK_FIELD_IS_WEAK;
1536 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1537 if (record->hasTrivialDestructor())
1538 continue;
1539 dtor = record->getDestructor();
1540 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001541 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001542 if (type->isBlockPointerType())
1543 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001544
John McCall31168b02011-06-15 23:02:42 +00001545 // Special rules for ARC captures.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001546 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001547 Qualifiers qs = type.getQualifiers();
1548
1549 // Don't generate special dispose logic for a captured object
1550 // unless it's __strong or __weak.
1551 if (!qs.hasStrongOrWeakObjCLifetime())
1552 continue;
1553
1554 // Support __weak direct captures.
1555 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak)
John McCalle68b8f42012-10-17 02:28:37 +00001556 useARCWeakDestroy = true;
1557
1558 // Tools really want us to use objc_storeStrong here.
1559 else
1560 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001561 }
1562 } else {
1563 continue;
1564 }
John McCall351762c2011-02-07 10:33:21 +00001565
1566 unsigned index = capture.getIndex();
David Blaikie1ed728c2015-04-05 22:45:47 +00001567 llvm::Value *srcField =
1568 Builder.CreateStructGEP(blockInfo.StructureType, src, index);
John McCall351762c2011-02-07 10:33:21 +00001569
1570 // If there's an explicit copy expression, we do that.
1571 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001572 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001573
John McCall31168b02011-06-15 23:02:42 +00001574 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001575 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001576 EmitARCDestroyWeak(srcField);
1577
John McCalle68b8f42012-10-17 02:28:37 +00001578 // Destroy strong objects with a call if requested.
1579 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001580 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001581
John McCall351762c2011-02-07 10:33:21 +00001582 // Otherwise we call _Block_object_dispose. It wouldn't be too
1583 // hard to just emit this as a cleanup if we wanted to make sure
1584 // that things were done in reverse.
1585 } else {
1586 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001587 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001588 BuildBlockRelease(value, flags);
1589 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001590 }
1591
John McCall351762c2011-02-07 10:33:21 +00001592 cleanups.ForceCleanup();
1593
John McCallad7c5c12011-02-08 08:22:06 +00001594 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001595
John McCalle3dc1702011-02-15 09:22:45 +00001596 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001597}
1598
John McCallf9b056b2011-03-31 08:03:29 +00001599namespace {
1600
1601/// Emits the copy/dispose helper functions for a __block object of id type.
David Blaikie92551612015-08-13 23:53:09 +00001602class ObjectByrefHelpers final : public CodeGenModule::ByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001603 BlockFieldFlags Flags;
1604
1605public:
1606 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
1607 : ByrefHelpers(alignment), Flags(flags) {}
1608
John McCall7c623642011-03-31 09:19:20 +00001609 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001610 llvm::Value *srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001611 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1612
1613 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1614 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1615
1616 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1617
1618 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1619 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001620
1621 llvm::Value *args[] = { destField, srcValue, flagsVal };
1622 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001623 }
1624
Craig Topper4f12f102014-03-12 06:41:41 +00001625 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001626 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1627 llvm::Value *value = CGF.Builder.CreateLoad(field);
1628
1629 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1630 }
1631
Craig Topper4f12f102014-03-12 06:41:41 +00001632 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001633 id.AddInteger(Flags.getBitMask());
1634 }
1635};
1636
John McCall31168b02011-06-15 23:02:42 +00001637/// Emits the copy/dispose helpers for an ARC __block __weak variable.
David Blaikie92551612015-08-13 23:53:09 +00001638class ARCWeakByrefHelpers final : public CodeGenModule::ByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001639public:
1640 ARCWeakByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1641
1642 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001643 llvm::Value *srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001644 CGF.EmitARCMoveWeak(destField, srcField);
1645 }
1646
Craig Topper4f12f102014-03-12 06:41:41 +00001647 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCall31168b02011-06-15 23:02:42 +00001648 CGF.EmitARCDestroyWeak(field);
1649 }
1650
Craig Topper4f12f102014-03-12 06:41:41 +00001651 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001652 // 0 is distinguishable from all pointers and byref flags
1653 id.AddInteger(0);
1654 }
1655};
1656
1657/// Emits the copy/dispose helpers for an ARC __block __strong variable
1658/// that's not of block-pointer type.
David Blaikie92551612015-08-13 23:53:09 +00001659class ARCStrongByrefHelpers final : public CodeGenModule::ByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001660public:
1661 ARCStrongByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1662
1663 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001664 llvm::Value *srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001665 // Do a "move" by copying the value and then zeroing out the old
1666 // variable.
1667
John McCall3a237aa2011-11-09 03:17:26 +00001668 llvm::LoadInst *value = CGF.Builder.CreateLoad(srcField);
1669 value->setAlignment(Alignment.getQuantity());
1670
John McCall31168b02011-06-15 23:02:42 +00001671 llvm::Value *null =
1672 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001673
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001674 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
Fariborz Jahaniancc2ae882013-01-05 00:32:13 +00001675 llvm::StoreInst *store = CGF.Builder.CreateStore(null, destField);
1676 store->setAlignment(Alignment.getQuantity());
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001677 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1678 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1679 return;
1680 }
John McCall3a237aa2011-11-09 03:17:26 +00001681 llvm::StoreInst *store = CGF.Builder.CreateStore(value, destField);
1682 store->setAlignment(Alignment.getQuantity());
1683
1684 store = CGF.Builder.CreateStore(null, srcField);
1685 store->setAlignment(Alignment.getQuantity());
John McCall31168b02011-06-15 23:02:42 +00001686 }
1687
Craig Topper4f12f102014-03-12 06:41:41 +00001688 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001689 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001690 }
1691
Craig Topper4f12f102014-03-12 06:41:41 +00001692 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001693 // 1 is distinguishable from all pointers and byref flags
1694 id.AddInteger(1);
1695 }
1696};
1697
John McCall3a237aa2011-11-09 03:17:26 +00001698/// Emits the copy/dispose helpers for an ARC __block __strong
1699/// variable that's of block-pointer type.
David Blaikie92551612015-08-13 23:53:09 +00001700class ARCStrongBlockByrefHelpers final : public CodeGenModule::ByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001701public:
1702 ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment) {}
1703
1704 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001705 llvm::Value *srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001706 // Do the copy with objc_retainBlock; that's all that
1707 // _Block_object_assign would do anyway, and we'd have to pass the
1708 // right arguments to make sure it doesn't get no-op'ed.
1709 llvm::LoadInst *oldValue = CGF.Builder.CreateLoad(srcField);
1710 oldValue->setAlignment(Alignment.getQuantity());
1711
1712 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
1713
1714 llvm::StoreInst *store = CGF.Builder.CreateStore(copy, destField);
1715 store->setAlignment(Alignment.getQuantity());
1716 }
1717
Craig Topper4f12f102014-03-12 06:41:41 +00001718 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001719 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001720 }
1721
Craig Topper4f12f102014-03-12 06:41:41 +00001722 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001723 // 2 is distinguishable from all pointers and byref flags
1724 id.AddInteger(2);
1725 }
1726};
1727
John McCallf9b056b2011-03-31 08:03:29 +00001728/// Emits the copy/dispose helpers for a __block variable with a
1729/// nontrivial copy constructor or destructor.
David Blaikie92551612015-08-13 23:53:09 +00001730class CXXByrefHelpers final : public CodeGenModule::ByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001731 QualType VarType;
1732 const Expr *CopyExpr;
1733
1734public:
1735 CXXByrefHelpers(CharUnits alignment, QualType type,
1736 const Expr *copyExpr)
1737 : ByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
1738
Craig Topper8a13c412014-05-21 05:09:00 +00001739 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCallf9b056b2011-03-31 08:03:29 +00001740 void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
Craig Topper4f12f102014-03-12 06:41:41 +00001741 llvm::Value *srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001742 if (!CopyExpr) return;
1743 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1744 }
1745
Craig Topper4f12f102014-03-12 06:41:41 +00001746 void emitDispose(CodeGenFunction &CGF, llvm::Value *field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001747 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1748 CGF.PushDestructorCleanup(VarType, field);
1749 CGF.PopCleanupBlocks(cleanupDepth);
1750 }
1751
Craig Topper4f12f102014-03-12 06:41:41 +00001752 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001753 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1754 }
1755};
1756} // end anonymous namespace
1757
1758static llvm::Constant *
1759generateByrefCopyHelper(CodeGenFunction &CGF,
Chris Lattner2192fe52011-07-18 04:24:23 +00001760 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001761 unsigned valueFieldIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001762 CodeGenModule::ByrefHelpers &byrefInfo) {
1763 ASTContext &Context = CGF.getContext();
1764
1765 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001766
John McCalla738c252011-03-09 04:27:21 +00001767 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001768 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001769 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001770 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001771
Craig Topper8a13c412014-05-21 05:09:00 +00001772 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001773 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001774 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Reid Kleckner4982b822014-01-31 22:54:50 +00001776 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1777 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001778
John McCallf9b056b2011-03-31 08:03:29 +00001779 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCalla729c622012-02-17 03:33:10 +00001780 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001781
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001782 // FIXME: We'd like to put these into a mergable by content, with
1783 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001784 llvm::Function *Fn =
1785 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001786 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001787
1788 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001789 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001790
John McCallf9b056b2011-03-31 08:03:29 +00001791 FunctionDecl *FD = FunctionDecl::Create(Context,
1792 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001793 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001794 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001795 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001796 false, false);
John McCall31168b02011-06-15 23:02:42 +00001797
Adrian Prantl22e66b42014-04-11 01:13:04 +00001798 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001799
John McCallf9b056b2011-03-31 08:03:29 +00001800 if (byrefInfo.needsCopy()) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001801 llvm::Type *byrefPtrType = byrefType.getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001802
John McCallf9b056b2011-03-31 08:03:29 +00001803 // dst->x
1804 llvm::Value *destField = CGF.GetAddrOfLocalVar(&dst);
1805 destField = CGF.Builder.CreateLoad(destField);
1806 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
David Blaikie2e804282015-04-05 22:47:07 +00001807 destField = CGF.Builder.CreateStructGEP(&byrefType, destField,
1808 valueFieldIndex, "x");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001809
John McCallf9b056b2011-03-31 08:03:29 +00001810 // src->x
1811 llvm::Value *srcField = CGF.GetAddrOfLocalVar(&src);
1812 srcField = CGF.Builder.CreateLoad(srcField);
1813 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
David Blaikie2e804282015-04-05 22:47:07 +00001814 srcField =
1815 CGF.Builder.CreateStructGEP(&byrefType, srcField, valueFieldIndex, "x");
John McCallf9b056b2011-03-31 08:03:29 +00001816
1817 byrefInfo.emitCopy(CGF, destField, srcField);
1818 }
1819
1820 CGF.FinishFunction();
1821
1822 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001823}
1824
John McCallf9b056b2011-03-31 08:03:29 +00001825/// Build the copy helper for a __block variable.
1826static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001827 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001828 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001829 CodeGenModule::ByrefHelpers &info) {
1830 CodeGenFunction CGF(CGM);
John McCallf593b102013-01-22 03:56:22 +00001831 return generateByrefCopyHelper(CGF, byrefType, byrefValueIndex, info);
John McCallf9b056b2011-03-31 08:03:29 +00001832}
1833
1834/// Generate code for a __block variable's dispose helper.
1835static llvm::Constant *
1836generateByrefDisposeHelper(CodeGenFunction &CGF,
Chris Lattner2192fe52011-07-18 04:24:23 +00001837 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001838 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001839 CodeGenModule::ByrefHelpers &byrefInfo) {
1840 ASTContext &Context = CGF.getContext();
1841 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001842
John McCalla738c252011-03-09 04:27:21 +00001843 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001844 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001845 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001846 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001847
Reid Kleckner4982b822014-01-31 22:54:50 +00001848 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1849 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001850
John McCallf9b056b2011-03-31 08:03:29 +00001851 CodeGenTypes &Types = CGF.CGM.getTypes();
John McCalla729c622012-02-17 03:33:10 +00001852 llvm::FunctionType *LTy = Types.GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001853
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001854 // FIXME: We'd like to put these into a mergable by content, with
1855 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001856 llvm::Function *Fn =
1857 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001858 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001859 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001860
1861 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001862 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001863
John McCallf9b056b2011-03-31 08:03:29 +00001864 FunctionDecl *FD = FunctionDecl::Create(Context,
1865 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001866 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001867 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001868 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001869 false, false);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001870 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001871
John McCallf9b056b2011-03-31 08:03:29 +00001872 if (byrefInfo.needsDispose()) {
1873 llvm::Value *V = CGF.GetAddrOfLocalVar(&src);
1874 V = CGF.Builder.CreateLoad(V);
1875 V = CGF.Builder.CreateBitCast(V, byrefType.getPointerTo(0));
David Blaikie1ed728c2015-04-05 22:45:47 +00001876 V = CGF.Builder.CreateStructGEP(&byrefType, V, byrefValueIndex, "x");
John McCallad7c5c12011-02-08 08:22:06 +00001877
John McCallf9b056b2011-03-31 08:03:29 +00001878 byrefInfo.emitDispose(CGF, V);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001879 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001880
John McCallf9b056b2011-03-31 08:03:29 +00001881 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001882
John McCallf9b056b2011-03-31 08:03:29 +00001883 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001884}
1885
John McCallf9b056b2011-03-31 08:03:29 +00001886/// Build the dispose helper for a __block variable.
1887static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001888 llvm::StructType &byrefType,
John McCallf593b102013-01-22 03:56:22 +00001889 unsigned byrefValueIndex,
John McCallf9b056b2011-03-31 08:03:29 +00001890 CodeGenModule::ByrefHelpers &info) {
1891 CodeGenFunction CGF(CGM);
John McCallf593b102013-01-22 03:56:22 +00001892 return generateByrefDisposeHelper(CGF, byrefType, byrefValueIndex, info);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001893}
1894
John McCallf593b102013-01-22 03:56:22 +00001895/// Lazily build the copy and dispose helpers for a __block variable
1896/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001897template <class T>
1898static T *buildByrefHelpers(CodeGenModule &CGM, llvm::StructType &byrefTy,
1899 unsigned byrefValueIndex, T byrefInfo) {
John McCallf9b056b2011-03-31 08:03:29 +00001900 // Increase the field's alignment to be at least pointer alignment,
1901 // since the layout of the byref struct will guarantee at least that.
1902 byrefInfo.Alignment = std::max(byrefInfo.Alignment,
1903 CharUnits::fromQuantity(CGM.PointerAlignInBytes));
1904
1905 llvm::FoldingSetNodeID id;
1906 byrefInfo.Profile(id);
1907
1908 void *insertPos;
1909 CodeGenModule::ByrefHelpers *node
1910 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1911 if (node) return static_cast<T*>(node);
1912
John McCallf593b102013-01-22 03:56:22 +00001913 byrefInfo.CopyHelper =
1914 buildByrefCopyHelper(CGM, byrefTy, byrefValueIndex, byrefInfo);
1915 byrefInfo.DisposeHelper =
1916 buildByrefDisposeHelper(CGM, byrefTy, byrefValueIndex,byrefInfo);
John McCallf9b056b2011-03-31 08:03:29 +00001917
David Blaikie92551612015-08-13 23:53:09 +00001918 T *copy = new (CGM.getContext()) T(std::move(byrefInfo));
John McCallf9b056b2011-03-31 08:03:29 +00001919 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1920 return copy;
1921}
1922
John McCallf593b102013-01-22 03:56:22 +00001923/// Build the copy and dispose helpers for the given __block variable
1924/// emission. Places the helpers in the global cache. Returns null
1925/// if no helpers are required.
John McCallf9b056b2011-03-31 08:03:29 +00001926CodeGenModule::ByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001927CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001928 const AutoVarEmission &emission) {
1929 const VarDecl &var = *emission.Variable;
1930 QualType type = var.getType();
1931
David Blaikie1ed728c2015-04-05 22:45:47 +00001932 unsigned byrefValueIndex = getByRefValueLLVMField(&var).second;
John McCallf593b102013-01-22 03:56:22 +00001933
John McCallf9b056b2011-03-31 08:03:29 +00001934 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1935 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001936 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001937
David Blaikie92551612015-08-13 23:53:09 +00001938 return ::buildByrefHelpers(
1939 CGM, byrefType, byrefValueIndex,
1940 CXXByrefHelpers(emission.Alignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001941 }
1942
John McCall31168b02011-06-15 23:02:42 +00001943 // Otherwise, if we don't have a retainable type, there's nothing to do.
1944 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001945 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001946
1947 Qualifiers qs = type.getQualifiers();
1948
1949 // If we have lifetime, that dominates.
1950 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001951 assert(getLangOpts().ObjCAutoRefCount);
John McCall31168b02011-06-15 23:02:42 +00001952
1953 switch (lifetime) {
1954 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1955
1956 // These are just bits as far as the runtime is concerned.
1957 case Qualifiers::OCL_ExplicitNone:
1958 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001959 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001960
1961 // Tell the runtime that this is ARC __weak, called by the
1962 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001963 case Qualifiers::OCL_Weak:
1964 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
1965 ARCWeakByrefHelpers(emission.Alignment));
John McCall31168b02011-06-15 23:02:42 +00001966
1967 // ARC __strong __block variables need to be retained.
1968 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001969 // Block pointers need to be copied, and there's no direct
1970 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001971 if (type->isBlockPointerType()) {
David Blaikie92551612015-08-13 23:53:09 +00001972 return ::buildByrefHelpers(
1973 CGM, byrefType, byrefValueIndex,
1974 ARCStrongBlockByrefHelpers(emission.Alignment));
John McCall31168b02011-06-15 23:02:42 +00001975
1976 // Otherwise, we transfer ownership of the retain from the stack
1977 // to the heap.
1978 } else {
David Blaikie92551612015-08-13 23:53:09 +00001979 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
1980 ARCStrongByrefHelpers(emission.Alignment));
John McCall31168b02011-06-15 23:02:42 +00001981 }
1982 }
1983 llvm_unreachable("fell out of lifetime switch!");
1984 }
1985
John McCallf9b056b2011-03-31 08:03:29 +00001986 BlockFieldFlags flags;
1987 if (type->isBlockPointerType()) {
1988 flags |= BLOCK_FIELD_IS_BLOCK;
1989 } else if (CGM.getContext().isObjCNSObjectType(type) ||
1990 type->isObjCObjectPointerType()) {
1991 flags |= BLOCK_FIELD_IS_OBJECT;
1992 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00001993 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001994 }
1995
1996 if (type.isObjCGCWeak())
1997 flags |= BLOCK_FIELD_IS_WEAK;
1998
David Blaikie92551612015-08-13 23:53:09 +00001999 return ::buildByrefHelpers(CGM, byrefType, byrefValueIndex,
2000 ObjectByrefHelpers(emission.Alignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002001}
2002
David Blaikie1ed728c2015-04-05 22:45:47 +00002003std::pair<llvm::Type *, unsigned>
2004CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
John McCall73064872011-03-31 01:59:53 +00002005 assert(ByRefValueInfo.count(VD) && "Did not find value!");
David Blaikie2e804282015-04-05 22:47:07 +00002006
David Blaikie1ed728c2015-04-05 22:45:47 +00002007 return ByRefValueInfo.find(VD)->second;
John McCall73064872011-03-31 01:59:53 +00002008}
2009
2010llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
2011 const VarDecl *V) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002012 auto P = getByRefValueLLVMField(V);
David Blaikie2e804282015-04-05 22:47:07 +00002013 llvm::Value *Loc =
2014 Builder.CreateStructGEP(P.first, BaseAddr, 1, "forwarding");
John McCall73064872011-03-31 01:59:53 +00002015 Loc = Builder.CreateLoad(Loc);
David Blaikie2e804282015-04-05 22:47:07 +00002016 Loc = Builder.CreateStructGEP(P.first, Loc, P.second, V->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002017 return Loc;
2018}
2019
2020/// BuildByRefType - This routine changes a __block variable declared as T x
2021/// into:
2022///
2023/// struct {
2024/// void *__isa;
2025/// void *__forwarding;
2026/// int32_t __flags;
2027/// int32_t __size;
2028/// void *__copy_helper; // only if needed
2029/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002030/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002031/// char padding[X]; // only if needed
2032/// T x;
2033/// } x
2034///
Chris Lattner2192fe52011-07-18 04:24:23 +00002035llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
2036 std::pair<llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
John McCall73064872011-03-31 01:59:53 +00002037 if (Info.first)
2038 return Info.first;
2039
2040 QualType Ty = D->getType();
2041
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002042 SmallVector<llvm::Type *, 8> types;
John McCall73064872011-03-31 01:59:53 +00002043
Chris Lattnera5f58b02011-07-09 17:41:47 +00002044 llvm::StructType *ByRefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002045 llvm::StructType::create(getLLVMContext(),
2046 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002047
2048 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002049 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002050
2051 // void *__forwarding;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002052 types.push_back(llvm::PointerType::getUnqual(ByRefType));
John McCall73064872011-03-31 01:59:53 +00002053
2054 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002055 types.push_back(Int32Ty);
John McCall73064872011-03-31 01:59:53 +00002056
2057 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002058 types.push_back(Int32Ty);
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002059 // Note that this must match *exactly* the logic in buildByrefHelpers.
2060 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
John McCall73064872011-03-31 01:59:53 +00002061 if (HasCopyAndDispose) {
2062 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002063 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002064
2065 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002066 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002067 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002068 bool HasByrefExtendedLayout = false;
2069 Qualifiers::ObjCLifetime Lifetime;
2070 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
2071 HasByrefExtendedLayout)
2072 /// void *__byref_variable_layout;
2073 types.push_back(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002074
2075 bool Packed = false;
2076 CharUnits Align = getContext().getDeclAlign(D);
John McCallc8e01702013-04-16 22:48:15 +00002077 if (Align >
2078 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
John McCall73064872011-03-31 01:59:53 +00002079 // We have to insert padding.
2080
2081 // The struct above has 2 32-bit integers.
2082 unsigned CurrentOffsetInBytes = 4 * 2;
2083
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002084 // And either 2, 3, 4 or 5 pointers.
2085 unsigned noPointers = 2;
2086 if (HasCopyAndDispose)
2087 noPointers += 2;
2088 if (HasByrefExtendedLayout)
2089 noPointers += 1;
2090
2091 CurrentOffsetInBytes += noPointers * CGM.getDataLayout().getTypeAllocSize(Int8PtrTy);
John McCall73064872011-03-31 01:59:53 +00002092
2093 // Align the offset.
2094 unsigned AlignedOffsetInBytes =
2095 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
2096
2097 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
2098 if (NumPaddingBytes > 0) {
Chris Lattnerece04092012-02-07 00:39:47 +00002099 llvm::Type *Ty = Int8Ty;
John McCall73064872011-03-31 01:59:53 +00002100 // FIXME: We need a sema error for alignment larger than the minimum of
John McCall9dc0db22011-05-15 01:53:33 +00002101 // the maximal stack alignment and the alignment of malloc on the system.
John McCall73064872011-03-31 01:59:53 +00002102 if (NumPaddingBytes > 1)
2103 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
2104
John McCall9dc0db22011-05-15 01:53:33 +00002105 types.push_back(Ty);
John McCall73064872011-03-31 01:59:53 +00002106
2107 // We want a packed struct.
2108 Packed = true;
2109 }
2110 }
2111
2112 // T x;
John McCall9dc0db22011-05-15 01:53:33 +00002113 types.push_back(ConvertTypeForMem(Ty));
John McCall73064872011-03-31 01:59:53 +00002114
Chris Lattnera5f58b02011-07-09 17:41:47 +00002115 ByRefType->setBody(types, Packed);
John McCall73064872011-03-31 01:59:53 +00002116
Chris Lattnera5f58b02011-07-09 17:41:47 +00002117 Info.first = ByRefType;
John McCall73064872011-03-31 01:59:53 +00002118
John McCall9dc0db22011-05-15 01:53:33 +00002119 Info.second = types.size() - 1;
John McCall73064872011-03-31 01:59:53 +00002120
2121 return Info.first;
2122}
2123
2124/// Initialize the structural components of a __block variable, i.e.
2125/// everything but the actual object.
2126void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002127 // Find the address of the local.
2128 llvm::Value *addr = emission.Address;
John McCall73064872011-03-31 01:59:53 +00002129
John McCallf9b056b2011-03-31 08:03:29 +00002130 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002131 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCallf9b056b2011-03-31 08:03:29 +00002132 cast<llvm::PointerType>(addr->getType())->getElementType());
2133
2134 // Build the byref helpers if necessary. This is null if we don't need any.
2135 CodeGenModule::ByrefHelpers *helpers =
2136 buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002137
2138 const VarDecl &D = *emission.Variable;
2139 QualType type = D.getType();
2140
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002141 bool HasByrefExtendedLayout;
2142 Qualifiers::ObjCLifetime ByrefLifetime;
2143 bool ByRefHasLifetime =
2144 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
2145
John McCallf9b056b2011-03-31 08:03:29 +00002146 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002147
2148 // Initialize the 'isa', which is just 0 or 1.
2149 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002150 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002151 isa = 1;
2152 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
David Blaikie2e804282015-04-05 22:47:07 +00002153 Builder.CreateStore(V,
2154 Builder.CreateStructGEP(nullptr, addr, 0, "byref.isa"));
John McCall73064872011-03-31 01:59:53 +00002155
2156 // Store the address of the variable into its own forwarding pointer.
David Blaikie2e804282015-04-05 22:47:07 +00002157 Builder.CreateStore(
2158 addr, Builder.CreateStructGEP(nullptr, addr, 1, "byref.forwarding"));
John McCall73064872011-03-31 01:59:53 +00002159
2160 // Blocks ABI:
2161 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002162 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002163 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002164 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2165 if (ByRefHasLifetime) {
2166 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2167 else switch (ByrefLifetime) {
2168 case Qualifiers::OCL_Strong:
2169 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2170 break;
2171 case Qualifiers::OCL_Weak:
2172 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2173 break;
2174 case Qualifiers::OCL_ExplicitNone:
2175 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2176 break;
2177 case Qualifiers::OCL_None:
2178 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2179 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2180 break;
2181 default:
2182 break;
2183 }
2184 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2185 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2186 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2187 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2188 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2189 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2190 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2191 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2192 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2193 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2194 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2195 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2196 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2197 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2198 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2199 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2200 }
2201 printf("\n");
2202 }
2203 }
David Blaikie2e804282015-04-05 22:47:07 +00002204
John McCall73064872011-03-31 01:59:53 +00002205 Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
David Blaikie1ed728c2015-04-05 22:45:47 +00002206 Builder.CreateStructGEP(nullptr, addr, 2, "byref.flags"));
John McCall73064872011-03-31 01:59:53 +00002207
John McCallf9b056b2011-03-31 08:03:29 +00002208 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2209 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
David Blaikie2e804282015-04-05 22:47:07 +00002210 Builder.CreateStore(V,
2211 Builder.CreateStructGEP(nullptr, addr, 3, "byref.size"));
John McCall73064872011-03-31 01:59:53 +00002212
John McCallf9b056b2011-03-31 08:03:29 +00002213 if (helpers) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002214 llvm::Value *copy_helper = Builder.CreateStructGEP(nullptr, addr, 4);
John McCallf9b056b2011-03-31 08:03:29 +00002215 Builder.CreateStore(helpers->CopyHelper, copy_helper);
John McCall73064872011-03-31 01:59:53 +00002216
David Blaikie1ed728c2015-04-05 22:45:47 +00002217 llvm::Value *destroy_helper = Builder.CreateStructGEP(nullptr, addr, 5);
John McCallf9b056b2011-03-31 08:03:29 +00002218 Builder.CreateStore(helpers->DisposeHelper, destroy_helper);
John McCall73064872011-03-31 01:59:53 +00002219 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002220 if (ByRefHasLifetime && HasByrefExtendedLayout) {
2221 llvm::Constant* ByrefLayoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
David Blaikie2e804282015-04-05 22:47:07 +00002222 llvm::Value *ByrefInfoAddr =
2223 Builder.CreateStructGEP(nullptr, addr, helpers ? 6 : 4, "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002224 // cast destination to pointer to source type.
2225 llvm::Type *DesTy = ByrefLayoutInfo->getType();
2226 DesTy = DesTy->getPointerTo();
2227 llvm::Value *BC = Builder.CreatePointerCast(ByrefInfoAddr, DesTy);
2228 Builder.CreateStore(ByrefLayoutInfo, BC);
2229 }
John McCall73064872011-03-31 01:59:53 +00002230}
2231
John McCallad7c5c12011-02-08 08:22:06 +00002232void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002233 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002234 llvm::Value *args[] = {
2235 Builder.CreateBitCast(V, Int8PtrTy),
2236 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2237 };
2238 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002239}
John McCall73064872011-03-31 01:59:53 +00002240
2241namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002242 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002243 llvm::Value *Addr;
2244 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2245
Craig Topper4f12f102014-03-12 06:41:41 +00002246 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002247 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002248 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2249 }
2250 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002251}
John McCall73064872011-03-31 01:59:53 +00002252
2253/// Enter a cleanup to destroy a __block variable. Note that this
2254/// cleanup should be a no-op if the variable hasn't left the stack
2255/// yet; if a cleanup is required for the variable itself, that needs
2256/// to be done externally.
2257void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2258 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002259 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002260 return;
2261
2262 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
2263}
John McCall7959fee2011-09-09 20:41:01 +00002264
2265/// Adjust the declaration of something from the blocks API.
2266static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2267 llvm::Constant *C) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002268 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall7959fee2011-09-09 20:41:01 +00002269
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002270 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002271 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002272 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2273}
2274
2275llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2276 if (BlockObjectDispose)
2277 return BlockObjectDispose;
2278
2279 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2280 llvm::FunctionType *fty
2281 = llvm::FunctionType::get(VoidTy, args, false);
2282 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2283 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2284 return BlockObjectDispose;
2285}
2286
2287llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2288 if (BlockObjectAssign)
2289 return BlockObjectAssign;
2290
2291 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2292 llvm::FunctionType *fty
2293 = llvm::FunctionType::get(VoidTy, args, false);
2294 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2295 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2296 return BlockObjectAssign;
2297}
2298
2299llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2300 if (NSConcreteGlobalBlock)
2301 return NSConcreteGlobalBlock;
2302
2303 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002304 Int8PtrTy->getPointerTo(),
2305 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002306 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2307 return NSConcreteGlobalBlock;
2308}
2309
2310llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2311 if (NSConcreteStackBlock)
2312 return NSConcreteStackBlock;
2313
2314 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002315 Int8PtrTy->getPointerTo(),
2316 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002317 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2318 return NSConcreteStackBlock;
2319}