blob: 3105046cff583acdd7450b52da752bc1a95f33a9 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
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),
John McCall7f416cc2015-09-08 08:05:57 +000033 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000034 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.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000043BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000044
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);
Hans Wennborgdcfba332015-10-06 23:40:43 +000081 llvm::Type *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000082 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(
John McCall7f416cc2015-09-08 08:05:57 +0000114 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), 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.
John McCall7f416cc2015-09-08 08:05:57 +0000206 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
207 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000208 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000209 info.CXXThisOffset = offset;
210 } else {
211 info.Captures.insert({Capture->getVariable(),
212 CGBlockInfo::Capture::makeIndex(index, offset)});
213 }
John McCall87fe5d52010-05-20 01:18:31 +0000214 }
John McCall351762c2011-02-07 10:33:21 +0000215 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000216
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000217 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000219 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000220 if (left.Alignment != right.Alignment)
221 return left.Alignment > right.Alignment;
222
223 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000224 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000225 return 1;
226 if (chunk.Lifetime == Qualifiers::OCL_Strong)
227 return 0;
228 if (chunk.Lifetime == Qualifiers::OCL_Weak)
229 return 2;
230 return 3;
231 };
232
233 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000234 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000235} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000236
John McCallb0a3ecb2011-02-08 03:07:00 +0000237/// Determines if the given type is safe for constant capture in C++.
238static bool isSafeForCXXConstantCapture(QualType type) {
239 const RecordType *recordType =
240 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
241
242 // Only records can be unsafe.
243 if (!recordType) return true;
244
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000245 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000246
247 // Maintain semantics for classes with non-trivial dtors or copy ctors.
248 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000249 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Otherwise, we just have to make sure there aren't any mutable
252 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000253 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000254}
255
John McCall351762c2011-02-07 10:33:21 +0000256/// It is illegal to modify a const object after initialization.
257/// Therefore, if a const object has a constant initializer, we don't
258/// actually need to keep storage for it in the block; we'll just
259/// rematerialize it at the start of the block function. This is
260/// acceptable because we make no promises about address stability of
261/// captured variables.
262static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000263 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000264 const VarDecl *var) {
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000265 // Return if this is a function paramter. We shouldn't try to
266 // rematerialize default arguments of function parameters.
267 if (isa<ParmVarDecl>(var))
268 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000269
John McCall351762c2011-02-07 10:33:21 +0000270 QualType type = var->getType();
271
272 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000273 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000274
John McCallb0a3ecb2011-02-08 03:07:00 +0000275 // Furthermore, in C++ we have to worry about mutable fields:
276 // C++ [dcl.type.cv]p4:
277 // Except that any class member declared mutable can be
278 // modified, any attempt to modify a const object during its
279 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000280 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000281 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000282
283 // If the variable doesn't have any initializer (shouldn't this be
284 // invalid?), it's not clear what we should do. Maybe capture as
285 // zero?
286 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000287 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000288
Richard Smithdafff942012-01-14 04:30:29 +0000289 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000290}
291
292/// Get the low bit of a nonzero character count. This is the
293/// alignment of the nth byte if the 0th byte is universally aligned.
294static CharUnits getLowBit(CharUnits v) {
295 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
296}
297
298static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000299 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000300 // The header is basically 'struct { void *; int; int; void *; void *; }'.
301 // Assert that that struct is packed.
302 assert(CGM.getIntSize() <= CGM.getPointerSize());
303 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
304 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000305
John McCall7f416cc2015-09-08 08:05:57 +0000306 info.BlockAlign = CGM.getPointerAlign();
307 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000308
309 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000310 elementTypes.push_back(CGM.VoidPtrTy);
311 elementTypes.push_back(CGM.IntTy);
312 elementTypes.push_back(CGM.IntTy);
313 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000314 elementTypes.push_back(CGM.getBlockDescriptorType());
315
316 assert(elementTypes.size() == BlockHeaderSize);
317}
318
319/// Compute the layout of the given block. Attempts to lay the block
320/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000321static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
322 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000323 ASTContext &C = CGM.getContext();
324 const BlockDecl *block = info.getBlockDecl();
325
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000327 initializeForBlockHeader(CGM, info, elementTypes);
328
329 if (!block->hasCaptures()) {
330 info.StructureType =
331 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
332 info.CanBeGlobal = true;
333 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000334 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000335 else if (C.getLangOpts().ObjC1 &&
336 CGM.getLangOpts().getGC() == LangOptions::NonGC)
337 info.HasCapturedVariableLayout = true;
338
John McCall351762c2011-02-07 10:33:21 +0000339 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000340 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000341 layout.reserve(block->capturesCXXThis() +
342 (block->capture_end() - block->capture_begin()));
343
344 CharUnits maxFieldAlign;
345
346 // First, 'this'.
347 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000348 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
349 "Can't capture 'this' outside a method");
350 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000351
John McCall7f416cc2015-09-08 08:05:57 +0000352 // Theoretically, this could be in a different address space, so
353 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000354 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000355 std::pair<CharUnits,CharUnits> tinfo
356 = CGM.getContext().getTypeInfoInChars(thisType);
357 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
358
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000359 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
360 Qualifiers::OCL_None,
Craig Topper8a13c412014-05-21 05:09:00 +0000361 nullptr, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000362 }
363
364 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000365 for (const auto &CI : block->captures()) {
366 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000367
Aaron Ballman9371dd22014-03-14 18:34:04 +0000368 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000369 // We have to copy/dispose of the __block reference.
370 info.NeedsCopyDispose = true;
371
John McCall351762c2011-02-07 10:33:21 +0000372 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000373 CharUnits align = CGM.getPointerAlign();
374 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000375
John McCall7f416cc2015-09-08 08:05:57 +0000376 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
377 Qualifiers::OCL_None, &CI,
378 CGM.VoidPtrTy));
John McCall351762c2011-02-07 10:33:21 +0000379 continue;
380 }
381
382 // Otherwise, build a layout chunk with the size and alignment of
383 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000384 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000385 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
386 continue;
387 }
388
John McCall31168b02011-06-15 23:02:42 +0000389 // If we have a lifetime qualifier, honor it for capture purposes.
390 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000391 Qualifiers::ObjCLifetime lifetime =
392 variable->getType().getObjCLifetime();
393 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000394 switch (lifetime) {
395 case Qualifiers::OCL_None: llvm_unreachable("impossible");
396 case Qualifiers::OCL_ExplicitNone:
397 case Qualifiers::OCL_Autoreleasing:
398 break;
John McCall351762c2011-02-07 10:33:21 +0000399
John McCall31168b02011-06-15 23:02:42 +0000400 case Qualifiers::OCL_Strong:
401 case Qualifiers::OCL_Weak:
402 info.NeedsCopyDispose = true;
403 }
404
405 // Block pointers require copy/dispose. So do Objective-C pointers.
406 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000407 // But honor the inert __unsafe_unretained qualifier, which doesn't
408 // actually make it into the type system.
409 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
410 lifetime = Qualifiers::OCL_ExplicitNone;
411 } else {
412 info.NeedsCopyDispose = true;
413 // used for mrr below.
414 lifetime = Qualifiers::OCL_Strong;
415 }
John McCall351762c2011-02-07 10:33:21 +0000416
417 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000418 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000419 info.NeedsCopyDispose = true;
420 info.HasCXXObject = true;
421
422 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000423 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000424 if (const CXXRecordDecl *record =
425 variable->getType()->getAsCXXRecordDecl()) {
426 if (!record->hasTrivialDestructor()) {
427 info.HasCXXObject = true;
428 info.NeedsCopyDispose = true;
429 }
430 }
431 }
432
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000433 QualType VT = variable->getType();
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000434 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000435 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000436
John McCall351762c2011-02-07 10:33:21 +0000437 maxFieldAlign = std::max(maxFieldAlign, align);
438
Jay Foad7c57be32011-07-11 09:56:20 +0000439 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000440 CGM.getTypes().ConvertTypeForMem(VT);
441
Aaron Ballman9371dd22014-03-14 18:34:04 +0000442 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000443 }
444
445 // If that was everything, we're done here.
446 if (layout.empty()) {
447 info.StructureType =
448 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
449 info.CanBeGlobal = true;
450 return;
451 }
452
453 // Sort the layout by alignment. We have to use a stable sort here
454 // to get reproducible results. There should probably be an
455 // llvm::array_pod_stable_sort.
456 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000457
458 // Needed for blocks layout info.
459 info.BlockHeaderForcedGapOffset = info.BlockSize;
460 info.BlockHeaderForcedGapSize = CharUnits::Zero();
461
John McCall351762c2011-02-07 10:33:21 +0000462 CharUnits &blockSize = info.BlockSize;
463 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
464
465 // Assuming that the first byte in the header is maximally aligned,
466 // get the alignment of the first byte following the header.
467 CharUnits endAlign = getLowBit(blockSize);
468
469 // If the end of the header isn't satisfactorily aligned for the
470 // maximum thing, look for things that are okay with the header-end
471 // alignment, and keep appending them until we get something that's
472 // aligned right. This algorithm is only guaranteed optimal if
473 // that condition is satisfied at some point; otherwise we can get
474 // things like:
475 // header // next byte has alignment 4
476 // something_with_size_5; // next byte has alignment 1
477 // something_with_alignment_8;
478 // which has 7 bytes of padding, as opposed to the naive solution
479 // which might have less (?).
480 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000481 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000482 li = layout.begin() + 1, le = layout.end();
483
484 // Look for something that the header end is already
485 // satisfactorily aligned for.
486 for (; li != le && endAlign < li->Alignment; ++li)
487 ;
488
489 // If we found something that's naturally aligned for the end of
490 // the header, keep adding things...
491 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000493 for (; li != le; ++li) {
494 assert(endAlign >= li->Alignment);
495
John McCall7f416cc2015-09-08 08:05:57 +0000496 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000497 elementTypes.push_back(li->Type);
498 blockSize += li->Size;
499 endAlign = getLowBit(blockSize);
500
501 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000502 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000503 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000504 }
John McCall351762c2011-02-07 10:33:21 +0000505 }
John McCall351762c2011-02-07 10:33:21 +0000506 // Don't re-append everything we just appended.
507 layout.erase(first, li);
508 }
509 }
510
John McCallac0350a2012-04-26 21:14:42 +0000511 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000512
John McCall351762c2011-02-07 10:33:21 +0000513 // At this point, we just have to add padding if the end align still
514 // isn't aligned right.
515 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000516 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000517 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000518
John McCall7f416cc2015-09-08 08:05:57 +0000519 // If we haven't yet added any fields, remember that there was an
520 // initial gap; this need to go into the block layout bit map.
521 if (blockSize == info.BlockHeaderForcedGapOffset) {
522 info.BlockHeaderForcedGapSize = padding;
523 }
524
John McCalle3dc1702011-02-15 09:22:45 +0000525 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
526 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000527 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000528 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000529 }
530
John McCall1db0a2f2012-05-01 20:28:00 +0000531 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000532 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000533 // Slam everything else on now. This works because they have
534 // strictly decreasing alignment and we expect that size is always a
535 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000536 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000537 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000538 if (endAlign < li->Alignment) {
539 // size may not be multiple of alignment. This can only happen with
540 // an over-aligned variable. We will be adding a padding field to
541 // make the size be multiple of alignment.
542 CharUnits padding = li->Alignment - endAlign;
543 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
544 padding.getQuantity()));
545 blockSize += padding;
546 endAlign = getLowBit(blockSize);
547 }
John McCall351762c2011-02-07 10:33:21 +0000548 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000549 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000550 elementTypes.push_back(li->Type);
551 blockSize += li->Size;
552 endAlign = getLowBit(blockSize);
553 }
554
555 info.StructureType =
556 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
557}
558
John McCall08ef4662011-11-10 08:15:53 +0000559/// Enter the scope of a block. This should be run at the entrance to
560/// a full-expression so that the block's cleanups are pushed at the
561/// right place in the stack.
562static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000563 assert(CGF.HaveInsertPoint());
564
John McCall08ef4662011-11-10 08:15:53 +0000565 // Allocate the block info and place it at the head of the list.
566 CGBlockInfo &blockInfo =
567 *new CGBlockInfo(block, CGF.CurFn->getName());
568 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
569 CGF.FirstBlockInfo = &blockInfo;
570
571 // Compute information about the layout, etc., of this block,
572 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000573 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000574
575 // Nothing else to do if it can be global.
576 if (blockInfo.CanBeGlobal) return;
577
578 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000579 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
580 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000581
582 // If there are cleanups to emit, enter them (but inactive).
583 if (!blockInfo.NeedsCopyDispose) return;
584
585 // Walk through the captures (in order) and find the ones not
586 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000587 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000588 // Ignore __block captures; there's nothing special in the
589 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000590 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000591
592 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000593 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000594 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
595 if (capture.isConstant()) continue;
596
597 // Ignore objects that aren't destructed.
598 QualType::DestructionKind dtorKind =
599 variable->getType().isDestructedType();
600 if (dtorKind == QualType::DK_none) continue;
601
602 CodeGenFunction::Destroyer *destroyer;
603
604 // Block captures count as local values and have imprecise semantics.
605 // They also can't be arrays, so need to worry about that.
606 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000607 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000608 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000609 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000610 }
611
612 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000613 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
614 capture.getIndex(),
615 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000616
John McCallf4beacd2011-11-10 10:43:54 +0000617 // We can use that GEP as the dominating IP.
618 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000619 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000620
John McCall08ef4662011-11-10 08:15:53 +0000621 CleanupKind cleanupKind = InactiveNormalCleanup;
622 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
623 if (useArrayEHCleanup)
624 cleanupKind = InactiveNormalAndEHCleanup;
625
626 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000627 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000628
629 // Remember where that cleanup was.
630 capture.setCleanup(CGF.EHStack.stable_begin());
631 }
632}
633
634/// Enter a full-expression with a non-trivial number of objects to
635/// clean up. This is in this file because, at the moment, the only
636/// kind of cleanup object is a BlockDecl*.
637void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
638 assert(E->getNumObjects() != 0);
639 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
640 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
641 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
642 enterBlockScope(*this, *i);
643 }
644}
645
646/// Find the layout for the given block in a linked list and remove it.
647static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
648 const BlockDecl *block) {
649 while (true) {
650 assert(head && *head);
651 CGBlockInfo *cur = *head;
652
653 // If this is the block we're looking for, splice it out of the list.
654 if (cur->getBlockDecl() == block) {
655 *head = cur->NextBlockInfo;
656 return cur;
657 }
658
659 head = &cur->NextBlockInfo;
660 }
661}
662
663/// Destroy a chain of block layouts.
664void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
665 assert(head && "destroying an empty chain");
666 do {
667 CGBlockInfo *cur = head;
668 head = cur->NextBlockInfo;
669 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000670 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000671}
672
John McCall351762c2011-02-07 10:33:21 +0000673/// Emit a block literal expression in the current function.
674llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000675 // If the block has no captures, we won't have a pre-computed
676 // layout for it.
677 if (!blockExpr->getBlockDecl()->hasCaptures()) {
678 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000679 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000680 blockInfo.BlockExpression = blockExpr;
681 return EmitBlockLiteral(blockInfo);
682 }
John McCall351762c2011-02-07 10:33:21 +0000683
John McCall08ef4662011-11-10 08:15:53 +0000684 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000685 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000686 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
687 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000688
John McCall08ef4662011-11-10 08:15:53 +0000689 blockInfo->BlockExpression = blockExpr;
690 return EmitBlockLiteral(*blockInfo);
691}
692
693llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
694 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000695 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000696 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000697 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000698 LocalDeclMap,
699 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000700 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000701
702 // If there is nothing to capture, we can emit this as a global block.
703 if (blockInfo.CanBeGlobal)
704 return buildGlobalBlock(CGM, blockInfo, blockFn);
705
706 // Otherwise, we have to emit this as a local block.
707
708 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000709 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000710
711 // Build the block descriptor.
712 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
713
John McCall7f416cc2015-09-08 08:05:57 +0000714 Address blockAddr = blockInfo.LocalAddress;
715 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000716
717 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000718 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000719 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000720 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
721 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000722 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000723
John McCall7f416cc2015-09-08 08:05:57 +0000724 auto projectField =
725 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
726 return Builder.CreateStructGEP(blockAddr, index, offset, name);
727 };
728 auto storeField =
729 [&](llvm::Value *value, unsigned index, CharUnits offset,
730 const Twine &name) {
731 Builder.CreateStore(value, projectField(index, offset, name));
732 };
733
734 // Initialize the block header.
735 {
736 // We assume all the header fields are densely packed.
737 unsigned index = 0;
738 CharUnits offset;
739 auto addHeaderField =
740 [&](llvm::Value *value, CharUnits size, const Twine &name) {
741 storeField(value, index, offset, name);
742 offset += size;
743 index++;
744 };
745
746 addHeaderField(isa, getPointerSize(), "block.isa");
747 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
748 getIntSize(), "block.flags");
749 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
750 getIntSize(), "block.reserved");
751 addHeaderField(blockFn, getPointerSize(), "block.invoke");
752 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
753 }
John McCall351762c2011-02-07 10:33:21 +0000754
755 // Finally, capture all the values into the block.
756 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
757
758 // First, 'this'.
759 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000760 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
761 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000762 Builder.CreateStore(LoadCXXThis(), addr);
763 }
764
765 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000766 for (const auto &CI : blockDecl->captures()) {
767 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000768 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
769
770 // Ignore constant captures.
771 if (capture.isConstant()) continue;
772
773 QualType type = variable->getType();
774
775 // This will be a [[type]]*, except that a byref entry will just be
776 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000777 Address blockField =
778 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000779
780 // Compute the address of the thing we're going to move into the
781 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000782 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000783
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000784 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000785 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000786 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000787 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000788 } else if (CI.isByRef()) {
789 if (BlockInfo && CI.isNested()) {
790 // We need to use the capture from the enclosing block.
791 const CGBlockInfo::Capture &enclosingCapture =
792 BlockInfo->getCapture(variable);
793
794 // This is a [[type]]*, except that a byref entry wil just be an i8**.
795 src = Builder.CreateStructGEP(LoadBlockStruct(),
796 enclosingCapture.getIndex(),
797 enclosingCapture.getOffset(),
798 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000799 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000800 auto I = LocalDeclMap.find(variable);
801 assert(I != LocalDeclMap.end());
802 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000803 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000804 } else {
805 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
806 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
807 type.getNonReferenceType(), VK_LValue,
808 SourceLocation());
809 src = EmitDeclRefLValue(&declRef).getAddress();
810 };
John McCall351762c2011-02-07 10:33:21 +0000811
812 // For byrefs, we just write the pointer to the byref struct into
813 // the block field. There's no need to chase the forwarding
814 // pointer at this point, since we're building something that will
815 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000816 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000817 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000818 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000819 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000820 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000821 else
John McCall7f416cc2015-09-08 08:05:57 +0000822 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000823
John McCalle3dc1702011-02-15 09:22:45 +0000824 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000825 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000826
827 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000828 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000829 if (blockDecl->isConversionFromLambda()) {
830 // If we have a lambda conversion, emit the expression
831 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000832 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000833 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000834 AggValueSlot::IsDestructed,
835 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000836 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000837 EmitAggExpr(copyExpr, Slot);
838 } else {
839 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
840 }
John McCall351762c2011-02-07 10:33:21 +0000841
842 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000843 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000844 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000845
846 // If this is an ARC __strong block-pointer variable, don't do a
847 // block copy.
848 //
849 // TODO: this can be generalized into the normal initialization logic:
850 // we should never need to do a block-copy when initializing a local
851 // variable, because the local variable's lifetime should be strictly
852 // contained within the stack block's.
853 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
854 type->isBlockPointerType()) {
855 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000856 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000857 value = EmitARCRetainNonBlock(value);
858
859 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000860 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000861
862 // Otherwise, fake up a POD copy into the block field.
863 } else {
John McCall31168b02011-06-15 23:02:42 +0000864 // Fake up a new variable so that EmitScalarInit doesn't think
865 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000866 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
867 SourceLocation(), /*name*/ nullptr,
868 type);
John McCall31168b02011-06-15 23:02:42 +0000869
John McCall93be3f72011-02-07 18:37:40 +0000870 // We use one of these or the other depending on whether the
871 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000872 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
873 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
874 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000875
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000876 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000877 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000878 // FIXME: Pass a specific location for the expr init so that the store is
879 // attributed to a reasonable location - otherwise it may be attributed to
880 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000881 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000882 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000883 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000884 }
885
John McCall08ef4662011-11-10 08:15:53 +0000886 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000887 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000888 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
889 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000890 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000891 }
John McCall351762c2011-02-07 10:33:21 +0000892 }
893
894 // Cast to the converted block-pointer type, which happens (somewhat
895 // unfortunately) to be a pointer to function type.
896 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000897 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000898 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000899
John McCall351762c2011-02-07 10:33:21 +0000900 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000901}
902
903
Chris Lattnera5f58b02011-07-09 17:41:47 +0000904llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000905 if (BlockDescriptorType)
906 return BlockDescriptorType;
907
Chris Lattnera5f58b02011-07-09 17:41:47 +0000908 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000909 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000910
Mike Stump650c9322009-02-13 15:16:56 +0000911 // struct __block_descriptor {
912 // unsigned long reserved;
913 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000914 //
915 // // later, the following will be added
916 //
917 // struct {
918 // void (*copyHelper)();
919 // void (*copyHelper)();
920 // } helpers; // !!! optional
921 //
922 // const char *signature; // the block signature
923 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000924 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000925 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000926 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000927 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000928
John McCall351762c2011-02-07 10:33:21 +0000929 // Now form a pointer to that.
930 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stump650c9322009-02-13 15:16:56 +0000931 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000932}
933
Chris Lattnera5f58b02011-07-09 17:41:47 +0000934llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000935 if (GenericBlockLiteralType)
936 return GenericBlockLiteralType;
937
Chris Lattnera5f58b02011-07-09 17:41:47 +0000938 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000939
Mike Stump005c9a62009-02-13 15:25:34 +0000940 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000941 // void *__isa;
942 // int __flags;
943 // int __reserved;
944 // void (*__invoke)(void *);
945 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000946 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000947 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000948 llvm::StructType::create("struct.__block_literal_generic",
949 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000950 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000951
Mike Stump005c9a62009-02-13 15:25:34 +0000952 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000953}
954
Nick Lewycky2d84e842013-10-02 02:29:49 +0000955RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000956 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000957 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000958 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000959
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000960 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
961
962 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000963 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000964 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000965
966 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000967 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000968 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
969
970 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000971 llvm::Value *FuncPtr =
972 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000973
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000974 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000975
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000976 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000977 CallArgList Args;
John McCall9dc0db22011-05-15 01:53:33 +0000978 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000979
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000980 QualType FnType = BPT->getPointeeType();
981
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000982 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +0000983 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +0000984
Anders Carlsson5f50c652009-04-07 22:10:22 +0000985 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +0000986 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +0000987
John McCall85915252011-03-09 08:39:33 +0000988 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +0000989 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +0000990 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Anders Carlsson5f50c652009-04-07 22:10:22 +0000992 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +0000993 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Chris Lattner2192fe52011-07-18 04:24:23 +0000995 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000996 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000997
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000998 // And call the block.
Anders Carlssonbfb36712009-12-24 21:13:40 +0000999 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001000}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001001
John McCall7f416cc2015-09-08 08:05:57 +00001002Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1003 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001004 assert(BlockInfo && "evaluating block ref without block information?");
1005 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001006
John McCall351762c2011-02-07 10:33:21 +00001007 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001008 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001009
John McCall7f416cc2015-09-08 08:05:57 +00001010 Address addr =
1011 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1012 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001013
John McCall351762c2011-02-07 10:33:21 +00001014 if (isByRef) {
1015 // addr should be a void** right now. Load, then cast the result
1016 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001017
John McCall7f416cc2015-09-08 08:05:57 +00001018 auto &byrefInfo = getBlockByrefInfo(variable);
1019 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001020
John McCall7f416cc2015-09-08 08:05:57 +00001021 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1022 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001023
John McCall7f416cc2015-09-08 08:05:57 +00001024 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1025 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001026 }
1027
John McCall7f416cc2015-09-08 08:05:57 +00001028 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1029 addr = EmitLoadOfReference(addr, refType);
1030 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00001031
John McCall351762c2011-02-07 10:33:21 +00001032 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001033}
1034
Mike Stump2d5a2872009-02-14 22:16:35 +00001035llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001036CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001037 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001038 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1039 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001040
John McCall351762c2011-02-07 10:33:21 +00001041 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001042 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001043
John McCall351762c2011-02-07 10:33:21 +00001044 // Using that metadata, generate the actual block function.
1045 llvm::Constant *blockFn;
1046 {
John McCall7f416cc2015-09-08 08:05:57 +00001047 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001048 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1049 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001050 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001051 false);
John McCall351762c2011-02-07 10:33:21 +00001052 }
John McCalle3dc1702011-02-15 09:22:45 +00001053 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001054
John McCallad7c5c12011-02-08 08:22:06 +00001055 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001056}
1057
John McCall351762c2011-02-07 10:33:21 +00001058static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1059 const CGBlockInfo &blockInfo,
1060 llvm::Constant *blockFn) {
1061 assert(blockInfo.CanBeGlobal);
1062
1063 // Generate the constants for the block literal initializer.
1064 llvm::Constant *fields[BlockHeaderSize];
1065
1066 // isa
1067 fields[0] = CGM.getNSConcreteGlobalBlock();
1068
1069 // __flags
John McCall85915252011-03-09 08:39:33 +00001070 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1071 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1072
John McCalle3dc1702011-02-15 09:22:45 +00001073 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001074
1075 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001076 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001077
1078 // Function
1079 fields[3] = blockFn;
1080
1081 // Descriptor
1082 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1083
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001084 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001085
1086 llvm::GlobalVariable *literal =
1087 new llvm::GlobalVariable(CGM.getModule(),
1088 init->getType(),
1089 /*constant*/ true,
1090 llvm::GlobalVariable::InternalLinkage,
1091 init,
1092 "__block_literal_global");
1093 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1094
1095 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001096 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001097 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1098 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001099}
1100
John McCall7f416cc2015-09-08 08:05:57 +00001101void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1102 unsigned argNum,
1103 llvm::Value *arg) {
1104 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1105
1106 llvm::Value *localAddr = nullptr;
1107 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1108 // Allocate a stack slot to let the debug info survive the RA.
1109 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1110 Builder.CreateStore(arg, alloc);
1111 localAddr = Builder.CreateLoad(alloc);
1112 }
1113
1114 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001115 if (CGM.getCodeGenOpts().getDebugInfo() >=
1116 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001117 DI->setLocation(D->getLocation());
1118 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1119 localAddr, Builder);
1120 }
1121 }
1122
1123 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1124 ApplyDebugLocation Scope(*this, StartLoc);
1125
1126 // Instead of messing around with LocalDeclMap, just set the value
1127 // directly as BlockPointer.
1128 BlockPointer = Builder.CreateBitCast(arg,
1129 BlockInfo->StructureType->getPointerTo(),
1130 "block");
1131}
1132
1133Address CodeGenFunction::LoadBlockStruct() {
1134 assert(BlockInfo && "not in a block invocation function!");
1135 assert(BlockPointer && "no block pointer set!");
1136 return Address(BlockPointer, BlockInfo->BlockAlign);
1137}
1138
Mike Stump4446dcf2009-03-05 08:32:30 +00001139llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001140CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1141 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001142 const DeclMapTy &ldm,
1143 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001144 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001145
Fariborz Jahanian63628032012-06-26 16:06:38 +00001146 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001147
1148 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001149
John McCall351762c2011-02-07 10:33:21 +00001150 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001151
Mike Stump5469f292009-03-13 23:34:28 +00001152 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001153 // to be local to this function as well, in case they're directly
1154 // referenced in a block.
1155 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001156 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001157 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001158 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001159 }
1160
John McCall351762c2011-02-07 10:33:21 +00001161 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001162
John McCall351762c2011-02-07 10:33:21 +00001163 // Build the argument list.
1164 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001165
John McCall351762c2011-02-07 10:33:21 +00001166 // The first argument is the block pointer. Just take it as a void*
1167 // and cast it later.
1168 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001169 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001170
Richard Smith053f6c62014-05-16 23:01:30 +00001171 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001172 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001173 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001174
John McCall351762c2011-02-07 10:33:21 +00001175 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001176 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001177
John McCall351762c2011-02-07 10:33:21 +00001178 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001179 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001180 const CGFunctionInfo &fnInfo =
1181 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001182 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001183 blockInfo.UsesStret = true;
1184
John McCalla729c622012-02-17 03:33:10 +00001185 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001186
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001187 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001188 llvm::Function *fn = llvm::Function::Create(
1189 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001190 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001191
John McCall351762c2011-02-07 10:33:21 +00001192 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001193 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001194 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001195 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001196
John McCall147d0212011-02-22 22:38:33 +00001197 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001198
Adrian Prantl0f6df002013-03-29 19:20:35 +00001199 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1200 // won't delete the dbg.declare intrinsics for captured variables.
1201 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1202 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1203 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001204 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1205 getPointerAlign(),
1206 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001207 // Set the DebugLocation to empty, so the store is recognized as a
1208 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001209 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001210 Builder.CreateStore(BlockPointer, Alloca);
1211 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001212 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001213
John McCall87fe5d52010-05-20 01:18:31 +00001214 // If we have a C++ 'this' reference, go ahead and force it into
1215 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001216 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001217 Address addr =
1218 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1219 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001220 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001221 }
1222
John McCall351762c2011-02-07 10:33:21 +00001223 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001224 for (const auto &CI : blockDecl->captures()) {
1225 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001226 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1227 if (!capture.isConstant()) continue;
1228
John McCall7f416cc2015-09-08 08:05:57 +00001229 CharUnits align = getContext().getDeclAlign(variable);
1230 Address alloca =
1231 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001232
John McCall7f416cc2015-09-08 08:05:57 +00001233 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001234
John McCall7f416cc2015-09-08 08:05:57 +00001235 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001236 }
1237
John McCall113bee02012-03-10 09:33:50 +00001238 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001239 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1240 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1241 --entry_ptr;
1242
Eli Friedman2495ab02012-02-25 02:48:22 +00001243 if (IsLambdaConversionToBlock)
1244 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001245 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001246 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001247 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001248 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001249 }
Mike Stump017460a2009-10-01 22:29:41 +00001250
Mike Stump7d699112009-10-01 00:27:30 +00001251 // Remember where we were...
1252 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001253
Mike Stump7d699112009-10-01 00:27:30 +00001254 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001255 ++entry_ptr;
1256 Builder.SetInsertPoint(entry, entry_ptr);
1257
John McCall113bee02012-03-10 09:33:50 +00001258 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001259 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001260 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001261 for (const auto &CI : blockDecl->captures()) {
1262 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001263 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001264
Benjamin Kramer8c305922016-02-02 11:06:51 +00001265 if (CGM.getCodeGenOpts().getDebugInfo() >=
1266 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001267 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1268 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001269 auto addr = LocalDeclMap.find(variable)->second;
1270 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001271 Builder);
1272 continue;
1273 }
John McCall351762c2011-02-07 10:33:21 +00001274
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001275 DI->EmitDeclareOfBlockDeclRefVariable(
1276 variable, BlockPointerDbgLoc, Builder, blockInfo,
1277 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001278 }
Mike Stump2e722b92009-09-30 02:43:10 +00001279 }
Manman Renab08a9a2013-01-04 18:51:35 +00001280 // Recover location if it was changed in the above loop.
1281 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001282 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001283 }
John McCall351762c2011-02-07 10:33:21 +00001284
Mike Stump7d699112009-10-01 00:27:30 +00001285 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001286 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001287 Builder.ClearInsertionPoint();
1288 else
1289 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001290
John McCall351762c2011-02-07 10:33:21 +00001291 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001292
John McCall351762c2011-02-07 10:33:21 +00001293 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001294}
Mike Stump1db7d042009-02-28 09:07:16 +00001295
John McCall351762c2011-02-07 10:33:21 +00001296/*
1297 notes.push_back(HelperInfo());
1298 HelperInfo &note = notes.back();
1299 note.index = capture.getIndex();
1300 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1301 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001302
John McCall351762c2011-02-07 10:33:21 +00001303 if (ci->isByRef()) {
1304 note.flag = BLOCK_FIELD_IS_BYREF;
1305 if (type.isObjCGCWeak())
1306 note.flag |= BLOCK_FIELD_IS_WEAK;
1307 } else if (type->isBlockPointerType()) {
1308 note.flag = BLOCK_FIELD_IS_BLOCK;
1309 } else {
1310 note.flag = BLOCK_FIELD_IS_OBJECT;
1311 }
1312 */
Mike Stump1db7d042009-02-28 09:07:16 +00001313
John McCallf593b102013-01-22 03:56:22 +00001314/// Generate the copy-helper function for a block closure object:
1315/// static void block_copy_helper(block_t *dst, block_t *src);
1316/// The runtime will have previously initialized 'dst' by doing a
1317/// bit-copy of 'src'.
1318///
1319/// Note that this copies an entire block closure object to the heap;
1320/// it should not be confused with a 'byref copy helper', which moves
1321/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001322llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001323CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001324 ASTContext &C = getContext();
1325
1326 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001327 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1328 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001329 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001330 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1331 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001332 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCallc56a8b32016-03-11 04:30:31 +00001334 const CGFunctionInfo &FI =
1335 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001336
John McCall351762c2011-02-07 10:33:21 +00001337 // FIXME: it would be nice if these were mergeable with things with
1338 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001339 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001340
1341 llvm::Function *Fn =
1342 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001343 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001344
1345 IdentifierInfo *II
1346 = &CGM.getContext().Idents.get("__copy_helper_block_");
1347
John McCall351762c2011-02-07 10:33:21 +00001348 FunctionDecl *FD = FunctionDecl::Create(C,
1349 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001350 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001351 SourceLocation(), II, C.VoidTy,
1352 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001353 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001354 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001355
1356 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1357
Adrian Prantl95b24e92015-02-03 20:00:54 +00001358 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001359 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001360 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001361 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001362 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001363
John McCall7f416cc2015-09-08 08:05:57 +00001364 Address src = GetAddrOfLocalVar(&srcDecl);
1365 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001366 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001367
John McCall7f416cc2015-09-08 08:05:57 +00001368 Address dst = GetAddrOfLocalVar(&dstDecl);
1369 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001370 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001371
John McCall351762c2011-02-07 10:33:21 +00001372 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001373
Aaron Ballman9371dd22014-03-14 18:34:04 +00001374 for (const auto &CI : blockDecl->captures()) {
1375 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001376 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001377
John McCall351762c2011-02-07 10:33:21 +00001378 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1379 if (capture.isConstant()) continue;
1380
Aaron Ballman9371dd22014-03-14 18:34:04 +00001381 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001382 BlockFieldFlags flags;
1383
John McCalle68b8f42012-10-17 02:28:37 +00001384 bool useARCWeakCopy = false;
1385 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001386
1387 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001388 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001389 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001390
Aaron Ballman9371dd22014-03-14 18:34:04 +00001391 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001392 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001393 if (type.isObjCGCWeak())
1394 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001395
John McCall31168b02011-06-15 23:02:42 +00001396 } else if (type->isObjCRetainableType()) {
1397 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001398 bool isBlockPointer = type->isBlockPointerType();
1399 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001400 flags = BLOCK_FIELD_IS_BLOCK;
1401
1402 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001403 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001404
John McCall460ce582015-10-22 18:38:17 +00001405 // We need to register __weak direct captures with the runtime.
1406 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1407 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001408
John McCall460ce582015-10-22 18:38:17 +00001409 // We need to retain the copied value for __strong direct captures.
1410 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1411 // If it's a block pointer, we have to copy the block and
1412 // assign that to the destination pointer, so we might as
1413 // well use _Block_object_assign. Otherwise we can avoid that.
1414 if (!isBlockPointer)
1415 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001416
1417 // Non-ARC captures of retainable pointers are strong and
1418 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001419 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001420 // fall through
John McCall460ce582015-10-22 18:38:17 +00001421
1422 // Otherwise the memcpy is fine.
1423 } else {
1424 continue;
John McCall31168b02011-06-15 23:02:42 +00001425 }
John McCall460ce582015-10-22 18:38:17 +00001426
1427 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001428 } else {
1429 continue;
1430 }
John McCall351762c2011-02-07 10:33:21 +00001431
1432 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001433 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1434 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001435
1436 // If there's an explicit copy expression, we do that.
1437 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001438 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001439 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001440 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001441 } else {
1442 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001443 if (useARCStrongCopy) {
1444 // At -O0, store null into the destination field (so that the
1445 // storeStrong doesn't over-release) and then call storeStrong.
1446 // This is a workaround to not having an initStrong call.
1447 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001448 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001449 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1450 Builder.CreateStore(null, dstField);
1451 EmitARCStoreStrongCall(dstField, srcValue, true);
1452
1453 // With optimization enabled, take advantage of the fact that
1454 // the blocks runtime guarantees a memcpy of the block data, and
1455 // just emit a retain of the src field.
1456 } else {
1457 EmitARCRetainNonBlock(srcValue);
1458
1459 // We don't need this anymore, so kill it. It's not quite
1460 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001461 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001462 }
1463 } else {
1464 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001465 llvm::Value *dstAddr =
1466 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001467 llvm::Value *args[] = {
1468 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1469 };
1470
1471 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001472 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001473 const Expr *copyExpr =
1474 CGM.getContext().getBlockVarCopyInits(variable);
1475 if (copyExpr) {
1476 copyCanThrow = true; // FIXME: reuse the noexcept logic
1477 }
1478 }
1479
1480 if (copyCanThrow) {
1481 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1482 } else {
1483 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1484 }
John McCalle68b8f42012-10-17 02:28:37 +00001485 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001486 }
1487 }
1488
John McCallad7c5c12011-02-08 08:22:06 +00001489 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001490
John McCalle3dc1702011-02-15 09:22:45 +00001491 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001492}
1493
John McCallf593b102013-01-22 03:56:22 +00001494/// Generate the destroy-helper function for a block closure object:
1495/// static void block_destroy_helper(block_t *theBlock);
1496///
1497/// Note that this destroys a heap-allocated block closure object;
1498/// it should not be confused with a 'byref destroy helper', which
1499/// destroys the heap-allocated contents of an individual __block
1500/// variable.
John McCall351762c2011-02-07 10:33:21 +00001501llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001502CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001503 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001504
John McCall351762c2011-02-07 10:33:21 +00001505 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001506 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1507 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001508 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001509
John McCallc56a8b32016-03-11 04:30:31 +00001510 const CGFunctionInfo &FI =
1511 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001512
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001513 // FIXME: We'd like to put these into a mergable by content, with
1514 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001515 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001516
1517 llvm::Function *Fn =
1518 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001519 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001520
1521 IdentifierInfo *II
1522 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1523
John McCall351762c2011-02-07 10:33:21 +00001524 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001525 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001526 SourceLocation(), II, C.VoidTy,
1527 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001528 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001529
1530 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1531
Adrian Prantl49a78562013-07-24 20:34:39 +00001532 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001533 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001534 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001535 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001536
Chris Lattner2192fe52011-07-18 04:24:23 +00001537 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001538
John McCall7f416cc2015-09-08 08:05:57 +00001539 Address src = GetAddrOfLocalVar(&srcDecl);
1540 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001541 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001542
John McCall351762c2011-02-07 10:33:21 +00001543 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1544
John McCallad7c5c12011-02-08 08:22:06 +00001545 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001546
Aaron Ballman9371dd22014-03-14 18:34:04 +00001547 for (const auto &CI : blockDecl->captures()) {
1548 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001549 QualType type = variable->getType();
1550
1551 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1552 if (capture.isConstant()) continue;
1553
John McCallad7c5c12011-02-08 08:22:06 +00001554 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001555 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001556
John McCalle68b8f42012-10-17 02:28:37 +00001557 bool useARCWeakDestroy = false;
1558 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001559
Aaron Ballman9371dd22014-03-14 18:34:04 +00001560 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001561 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001562 if (type.isObjCGCWeak())
1563 flags |= BLOCK_FIELD_IS_WEAK;
1564 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1565 if (record->hasTrivialDestructor())
1566 continue;
1567 dtor = record->getDestructor();
1568 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001569 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001570 if (type->isBlockPointerType())
1571 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001572
John McCall31168b02011-06-15 23:02:42 +00001573 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001574 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001575
John McCall460ce582015-10-22 18:38:17 +00001576 // Use objc_storeStrong for __strong direct captures; the
1577 // dynamic tools really like it when we do this.
1578 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1579 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001580
John McCall460ce582015-10-22 18:38:17 +00001581 // Support __weak direct captures.
1582 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1583 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001584
John McCall460ce582015-10-22 18:38:17 +00001585 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1586 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1587 // fall through
1588
1589 // Otherwise, we have nothing to do.
1590 } else {
1591 continue;
John McCall31168b02011-06-15 23:02:42 +00001592 }
1593 } else {
1594 continue;
1595 }
John McCall351762c2011-02-07 10:33:21 +00001596
John McCall7f416cc2015-09-08 08:05:57 +00001597 Address srcField =
1598 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001599
1600 // If there's an explicit copy expression, we do that.
1601 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001602 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001603
John McCall31168b02011-06-15 23:02:42 +00001604 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001605 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001606 EmitARCDestroyWeak(srcField);
1607
John McCalle68b8f42012-10-17 02:28:37 +00001608 // Destroy strong objects with a call if requested.
1609 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001610 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001611
John McCall351762c2011-02-07 10:33:21 +00001612 // Otherwise we call _Block_object_dispose. It wouldn't be too
1613 // hard to just emit this as a cleanup if we wanted to make sure
1614 // that things were done in reverse.
1615 } else {
1616 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001617 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001618 BuildBlockRelease(value, flags);
1619 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001620 }
1621
John McCall351762c2011-02-07 10:33:21 +00001622 cleanups.ForceCleanup();
1623
John McCallad7c5c12011-02-08 08:22:06 +00001624 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001625
John McCalle3dc1702011-02-15 09:22:45 +00001626 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001627}
1628
John McCallf9b056b2011-03-31 08:03:29 +00001629namespace {
1630
1631/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001632class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001633 BlockFieldFlags Flags;
1634
1635public:
1636 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001637 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001638
John McCall7f416cc2015-09-08 08:05:57 +00001639 void emitCopy(CodeGenFunction &CGF, Address destField,
1640 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001641 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1642
1643 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1644 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1645
1646 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1647
1648 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1649 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001650
John McCall7f416cc2015-09-08 08:05:57 +00001651 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001652 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001653 }
1654
John McCall7f416cc2015-09-08 08:05:57 +00001655 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001656 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1657 llvm::Value *value = CGF.Builder.CreateLoad(field);
1658
1659 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1660 }
1661
Craig Topper4f12f102014-03-12 06:41:41 +00001662 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001663 id.AddInteger(Flags.getBitMask());
1664 }
1665};
1666
John McCall31168b02011-06-15 23:02:42 +00001667/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001668class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001669public:
John McCall7f416cc2015-09-08 08:05:57 +00001670 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001671
John McCall7f416cc2015-09-08 08:05:57 +00001672 void emitCopy(CodeGenFunction &CGF, Address destField,
1673 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001674 CGF.EmitARCMoveWeak(destField, srcField);
1675 }
1676
John McCall7f416cc2015-09-08 08:05:57 +00001677 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001678 CGF.EmitARCDestroyWeak(field);
1679 }
1680
Craig Topper4f12f102014-03-12 06:41:41 +00001681 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001682 // 0 is distinguishable from all pointers and byref flags
1683 id.AddInteger(0);
1684 }
1685};
1686
1687/// Emits the copy/dispose helpers for an ARC __block __strong variable
1688/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001689class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001690public:
John McCall7f416cc2015-09-08 08:05:57 +00001691 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 void emitCopy(CodeGenFunction &CGF, Address destField,
1694 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001695 // Do a "move" by copying the value and then zeroing out the old
1696 // variable.
1697
John McCall7f416cc2015-09-08 08:05:57 +00001698 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001699
John McCall31168b02011-06-15 23:02:42 +00001700 llvm::Value *null =
1701 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001702
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001703 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001704 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001705 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1706 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1707 return;
1708 }
John McCall7f416cc2015-09-08 08:05:57 +00001709 CGF.Builder.CreateStore(value, destField);
1710 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001711 }
1712
John McCall7f416cc2015-09-08 08:05:57 +00001713 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001714 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001715 }
1716
Craig Topper4f12f102014-03-12 06:41:41 +00001717 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001718 // 1 is distinguishable from all pointers and byref flags
1719 id.AddInteger(1);
1720 }
1721};
1722
John McCall3a237aa2011-11-09 03:17:26 +00001723/// Emits the copy/dispose helpers for an ARC __block __strong
1724/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001725class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001726public:
John McCall7f416cc2015-09-08 08:05:57 +00001727 ARCStrongBlockByrefHelpers(CharUnits alignment)
1728 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001729
John McCall7f416cc2015-09-08 08:05:57 +00001730 void emitCopy(CodeGenFunction &CGF, Address destField,
1731 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001732 // Do the copy with objc_retainBlock; that's all that
1733 // _Block_object_assign would do anyway, and we'd have to pass the
1734 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001735 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001736 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001737 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001738 }
1739
John McCall7f416cc2015-09-08 08:05:57 +00001740 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001741 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001742 }
1743
Craig Topper4f12f102014-03-12 06:41:41 +00001744 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001745 // 2 is distinguishable from all pointers and byref flags
1746 id.AddInteger(2);
1747 }
1748};
1749
John McCallf9b056b2011-03-31 08:03:29 +00001750/// Emits the copy/dispose helpers for a __block variable with a
1751/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001752class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001753 QualType VarType;
1754 const Expr *CopyExpr;
1755
1756public:
1757 CXXByrefHelpers(CharUnits alignment, QualType type,
1758 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001759 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001760
Craig Topper8a13c412014-05-21 05:09:00 +00001761 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001762 void emitCopy(CodeGenFunction &CGF, Address destField,
1763 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001764 if (!CopyExpr) return;
1765 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1766 }
1767
John McCall7f416cc2015-09-08 08:05:57 +00001768 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001769 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1770 CGF.PushDestructorCleanup(VarType, field);
1771 CGF.PopCleanupBlocks(cleanupDepth);
1772 }
1773
Craig Topper4f12f102014-03-12 06:41:41 +00001774 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001775 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1776 }
1777};
1778} // end anonymous namespace
1779
1780static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001781generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1782 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001783 ASTContext &Context = CGF.getContext();
1784
1785 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001786
John McCalla738c252011-03-09 04:27:21 +00001787 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001788 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001789 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001790 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001791
Craig Topper8a13c412014-05-21 05:09:00 +00001792 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001793 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001794 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001795
John McCallc56a8b32016-03-11 04:30:31 +00001796 const CGFunctionInfo &FI =
1797 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001798
John McCall7f416cc2015-09-08 08:05:57 +00001799 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001800
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001801 // FIXME: We'd like to put these into a mergable by content, with
1802 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001803 llvm::Function *Fn =
1804 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001805 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001806
1807 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001808 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001809
John McCallf9b056b2011-03-31 08:03:29 +00001810 FunctionDecl *FD = FunctionDecl::Create(Context,
1811 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001812 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001813 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001814 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001815 false, false);
John McCall31168b02011-06-15 23:02:42 +00001816
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001817 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1818
Adrian Prantl22e66b42014-04-11 01:13:04 +00001819 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001820
John McCall7f416cc2015-09-08 08:05:57 +00001821 if (generator.needsCopy()) {
1822 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001823
John McCallf9b056b2011-03-31 08:03:29 +00001824 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address destField = CGF.GetAddrOfLocalVar(&dst);
1826 destField = Address(CGF.Builder.CreateLoad(destField),
1827 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001828 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001829 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1830 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001831
John McCallf9b056b2011-03-31 08:03:29 +00001832 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001833 Address srcField = CGF.GetAddrOfLocalVar(&src);
1834 srcField = Address(CGF.Builder.CreateLoad(srcField),
1835 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001836 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001837 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1838 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001839
John McCall7f416cc2015-09-08 08:05:57 +00001840 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001841 }
1842
1843 CGF.FinishFunction();
1844
1845 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001846}
1847
John McCallf9b056b2011-03-31 08:03:29 +00001848/// Build the copy helper for a __block variable.
1849static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001850 const BlockByrefInfo &byrefInfo,
1851 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001852 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001853 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001854}
1855
1856/// Generate code for a __block variable's dispose helper.
1857static llvm::Constant *
1858generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001859 const BlockByrefInfo &byrefInfo,
1860 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001861 ASTContext &Context = CGF.getContext();
1862 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001863
John McCalla738c252011-03-09 04:27:21 +00001864 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001865 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001866 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001867 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001868
John McCallc56a8b32016-03-11 04:30:31 +00001869 const CGFunctionInfo &FI =
1870 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001871
John McCall7f416cc2015-09-08 08:05:57 +00001872 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001873
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001874 // FIXME: We'd like to put these into a mergable by content, with
1875 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001876 llvm::Function *Fn =
1877 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001878 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001879 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001880
1881 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001882 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001883
John McCallf9b056b2011-03-31 08:03:29 +00001884 FunctionDecl *FD = FunctionDecl::Create(Context,
1885 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001886 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001887 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001888 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001889 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001890
1891 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1892
Adrian Prantl22e66b42014-04-11 01:13:04 +00001893 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001894
John McCall7f416cc2015-09-08 08:05:57 +00001895 if (generator.needsDispose()) {
1896 Address addr = CGF.GetAddrOfLocalVar(&src);
1897 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1898 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1899 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1900 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001901
John McCall7f416cc2015-09-08 08:05:57 +00001902 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001903 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001904
John McCallf9b056b2011-03-31 08:03:29 +00001905 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001906
John McCallf9b056b2011-03-31 08:03:29 +00001907 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001908}
1909
John McCallf9b056b2011-03-31 08:03:29 +00001910/// Build the dispose helper for a __block variable.
1911static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001912 const BlockByrefInfo &byrefInfo,
1913 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001914 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001915 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001916}
1917
John McCallf593b102013-01-22 03:56:22 +00001918/// Lazily build the copy and dispose helpers for a __block variable
1919/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001920template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001921static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1922 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001923 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001924 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001925
1926 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001927 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001928 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1929 if (node) return static_cast<T*>(node);
1930
John McCall7f416cc2015-09-08 08:05:57 +00001931 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1932 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001933
John McCall7f416cc2015-09-08 08:05:57 +00001934 T *copy = new (CGM.getContext()) T(std::move(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001935 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1936 return copy;
1937}
1938
John McCallf593b102013-01-22 03:56:22 +00001939/// Build the copy and dispose helpers for the given __block variable
1940/// emission. Places the helpers in the global cache. Returns null
1941/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001942BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001943CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001944 const AutoVarEmission &emission) {
1945 const VarDecl &var = *emission.Variable;
1946 QualType type = var.getType();
1947
John McCall7f416cc2015-09-08 08:05:57 +00001948 auto &byrefInfo = getBlockByrefInfo(&var);
1949
1950 // The alignment we care about for the purposes of uniquing byref
1951 // helpers is the alignment of the actual byref value field.
1952 CharUnits valueAlignment =
1953 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001954
John McCallf9b056b2011-03-31 08:03:29 +00001955 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1956 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001957 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001958
David Blaikie92551612015-08-13 23:53:09 +00001959 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001960 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001961 }
1962
John McCall31168b02011-06-15 23:02:42 +00001963 // Otherwise, if we don't have a retainable type, there's nothing to do.
1964 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001965 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001966
1967 Qualifiers qs = type.getQualifiers();
1968
1969 // If we have lifetime, that dominates.
1970 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001971 switch (lifetime) {
1972 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1973
1974 // These are just bits as far as the runtime is concerned.
1975 case Qualifiers::OCL_ExplicitNone:
1976 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001977 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001978
1979 // Tell the runtime that this is ARC __weak, called by the
1980 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001981 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00001982 return ::buildByrefHelpers(CGM, byrefInfo,
1983 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001984
1985 // ARC __strong __block variables need to be retained.
1986 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001987 // Block pointers need to be copied, and there's no direct
1988 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001989 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001990 return ::buildByrefHelpers(CGM, byrefInfo,
1991 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001992
1993 // Otherwise, we transfer ownership of the retain from the stack
1994 // to the heap.
1995 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001996 return ::buildByrefHelpers(CGM, byrefInfo,
1997 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001998 }
1999 }
2000 llvm_unreachable("fell out of lifetime switch!");
2001 }
2002
John McCallf9b056b2011-03-31 08:03:29 +00002003 BlockFieldFlags flags;
2004 if (type->isBlockPointerType()) {
2005 flags |= BLOCK_FIELD_IS_BLOCK;
2006 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2007 type->isObjCObjectPointerType()) {
2008 flags |= BLOCK_FIELD_IS_OBJECT;
2009 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002010 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002011 }
2012
2013 if (type.isObjCGCWeak())
2014 flags |= BLOCK_FIELD_IS_WEAK;
2015
John McCall7f416cc2015-09-08 08:05:57 +00002016 return ::buildByrefHelpers(CGM, byrefInfo,
2017 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002018}
2019
John McCall7f416cc2015-09-08 08:05:57 +00002020Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2021 const VarDecl *var,
2022 bool followForward) {
2023 auto &info = getBlockByrefInfo(var);
2024 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002025}
2026
John McCall7f416cc2015-09-08 08:05:57 +00002027Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2028 const BlockByrefInfo &info,
2029 bool followForward,
2030 const llvm::Twine &name) {
2031 // Chase the forwarding address if requested.
2032 if (followForward) {
2033 Address forwardingAddr =
2034 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2035 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2036 }
2037
2038 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2039 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002040}
2041
John McCall7f416cc2015-09-08 08:05:57 +00002042/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002043/// into:
2044///
2045/// struct {
2046/// void *__isa;
2047/// void *__forwarding;
2048/// int32_t __flags;
2049/// int32_t __size;
2050/// void *__copy_helper; // only if needed
2051/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002052/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002053/// char padding[X]; // only if needed
2054/// T x;
2055/// } x
2056///
John McCall7f416cc2015-09-08 08:05:57 +00002057const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2058 auto it = BlockByrefInfos.find(D);
2059 if (it != BlockByrefInfos.end())
2060 return it->second;
John McCall73064872011-03-31 01:59:53 +00002061
John McCall7f416cc2015-09-08 08:05:57 +00002062 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002063 llvm::StructType::create(getLLVMContext(),
2064 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002065
John McCall7f416cc2015-09-08 08:05:57 +00002066 QualType Ty = D->getType();
2067
2068 CharUnits size;
2069 SmallVector<llvm::Type *, 8> types;
2070
John McCall73064872011-03-31 01:59:53 +00002071 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002072 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002073 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002074
2075 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002076 types.push_back(llvm::PointerType::getUnqual(byrefType));
2077 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002078
2079 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002080 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002081 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002082
2083 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002084 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002085 size += CharUnits::fromQuantity(4);
2086
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002087 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002088 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2089 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002090 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002091 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002092 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002093
2094 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002095 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002096 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002097 }
John McCall7f416cc2015-09-08 08:05:57 +00002098
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002099 bool HasByrefExtendedLayout = false;
2100 Qualifiers::ObjCLifetime Lifetime;
2101 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002102 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002103 /// void *__byref_variable_layout;
2104 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002105 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002106 }
2107
2108 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002109 llvm::Type *varTy = ConvertTypeForMem(Ty);
2110
2111 bool packed = false;
2112 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002113 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002114
2115 // We may have to insert padding.
2116 if (varOffset != size) {
2117 llvm::Type *paddingTy =
2118 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2119
2120 types.push_back(paddingTy);
2121 size = varOffset;
2122
2123 // Conversely, we might have to prevent LLVM from inserting padding.
2124 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2125 > varAlign.getQuantity()) {
2126 packed = true;
2127 }
2128 types.push_back(varTy);
2129
2130 byrefType->setBody(types, packed);
2131
2132 BlockByrefInfo info;
2133 info.Type = byrefType;
2134 info.FieldIndex = types.size() - 1;
2135 info.FieldOffset = varOffset;
2136 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2137
2138 auto pair = BlockByrefInfos.insert({D, info});
2139 assert(pair.second && "info was inserted recursively?");
2140 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002141}
2142
2143/// Initialize the structural components of a __block variable, i.e.
2144/// everything but the actual object.
2145void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002146 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002147 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002148
John McCallf9b056b2011-03-31 08:03:29 +00002149 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002150 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002151 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2152
2153 unsigned nextHeaderIndex = 0;
2154 CharUnits nextHeaderOffset;
2155 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2156 const Twine &name) {
2157 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2158 nextHeaderOffset, name);
2159 Builder.CreateStore(value, fieldAddr);
2160
2161 nextHeaderIndex++;
2162 nextHeaderOffset += fieldSize;
2163 };
John McCallf9b056b2011-03-31 08:03:29 +00002164
2165 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002166 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002167
2168 const VarDecl &D = *emission.Variable;
2169 QualType type = D.getType();
2170
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002171 bool HasByrefExtendedLayout;
2172 Qualifiers::ObjCLifetime ByrefLifetime;
2173 bool ByRefHasLifetime =
2174 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002175
John McCallf9b056b2011-03-31 08:03:29 +00002176 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002177
2178 // Initialize the 'isa', which is just 0 or 1.
2179 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002180 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002181 isa = 1;
2182 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002183 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002184
2185 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002186 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002187
2188 // Blocks ABI:
2189 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002190 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002191 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002192 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2193 if (ByRefHasLifetime) {
2194 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2195 else switch (ByrefLifetime) {
2196 case Qualifiers::OCL_Strong:
2197 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2198 break;
2199 case Qualifiers::OCL_Weak:
2200 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2201 break;
2202 case Qualifiers::OCL_ExplicitNone:
2203 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2204 break;
2205 case Qualifiers::OCL_None:
2206 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2207 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2208 break;
2209 default:
2210 break;
2211 }
2212 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2213 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2214 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2215 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2216 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2217 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2218 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2219 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2220 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2221 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2222 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2223 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2224 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2225 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2226 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2227 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2228 }
2229 printf("\n");
2230 }
2231 }
John McCall7f416cc2015-09-08 08:05:57 +00002232 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2233 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002234
John McCallf9b056b2011-03-31 08:03:29 +00002235 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2236 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002237 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002238
John McCallf9b056b2011-03-31 08:03:29 +00002239 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002240 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2241 "byref.copyHelper");
2242 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2243 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002244 }
John McCall7f416cc2015-09-08 08:05:57 +00002245
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002246 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002247 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2248 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002249 }
John McCall73064872011-03-31 01:59:53 +00002250}
2251
John McCallad7c5c12011-02-08 08:22:06 +00002252void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002253 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002254 llvm::Value *args[] = {
2255 Builder.CreateBitCast(V, Int8PtrTy),
2256 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2257 };
2258 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002259}
John McCall73064872011-03-31 01:59:53 +00002260
2261namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002262 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002263 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002264 llvm::Value *Addr;
2265 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2266
Craig Topper4f12f102014-03-12 06:41:41 +00002267 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002268 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002269 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2270 }
2271 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002272} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002273
2274/// Enter a cleanup to destroy a __block variable. Note that this
2275/// cleanup should be a no-op if the variable hasn't left the stack
2276/// yet; if a cleanup is required for the variable itself, that needs
2277/// to be done externally.
2278void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2279 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002280 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002281 return;
2282
John McCall7f416cc2015-09-08 08:05:57 +00002283 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2284 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002285}
John McCall7959fee2011-09-09 20:41:01 +00002286
2287/// Adjust the declaration of something from the blocks API.
2288static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2289 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002290 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002291
2292 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2293 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2294 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2295 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2296
2297 assert((isa<llvm::Function>(C) || isa<llvm::GlobalValue>(C)) &&
2298 "expected Function or GlobalValue");
2299
2300 const NamedDecl *ND = nullptr;
2301 for (const auto &Result : DC->lookup(&II))
2302 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2303 (ND = dyn_cast<VarDecl>(Result)))
2304 break;
2305
2306 // TODO: support static blocks runtime
2307 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2308 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2309 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2310 } else {
2311 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2312 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2313 }
2314 }
2315
2316 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2317 return;
2318
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002319 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002320 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2321}
2322
2323llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2324 if (BlockObjectDispose)
2325 return BlockObjectDispose;
2326
2327 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2328 llvm::FunctionType *fty
2329 = llvm::FunctionType::get(VoidTy, args, false);
2330 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2331 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2332 return BlockObjectDispose;
2333}
2334
2335llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2336 if (BlockObjectAssign)
2337 return BlockObjectAssign;
2338
2339 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2340 llvm::FunctionType *fty
2341 = llvm::FunctionType::get(VoidTy, args, false);
2342 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2343 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2344 return BlockObjectAssign;
2345}
2346
2347llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2348 if (NSConcreteGlobalBlock)
2349 return NSConcreteGlobalBlock;
2350
2351 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002352 Int8PtrTy->getPointerTo(),
2353 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002354 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2355 return NSConcreteGlobalBlock;
2356}
2357
2358llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2359 if (NSConcreteStackBlock)
2360 return NSConcreteStackBlock;
2361
2362 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002363 Int8PtrTy->getPointerTo(),
2364 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002365 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002366 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002367}