blob: 933cd2a62cc46b1f02c7483ddbee8ce25851b795 [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
Joey Goulyddbda402016-08-10 15:57:02 +0000128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall351762c2011-02-07 10:33:21 +0000131 llvm::GlobalVariable *global =
132 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
133 llvm::GlobalValue::InternalLinkage,
Joey Goulyddbda402016-08-10 15:57:02 +0000134 init, "__block_descriptor_tmp", nullptr,
135 llvm::GlobalValue::NotThreadLocal,
136 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000137
John McCall351762c2011-02-07 10:33:21 +0000138 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000139}
140
John McCall351762c2011-02-07 10:33:21 +0000141/*
142 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000143
John McCall351762c2011-02-07 10:33:21 +0000144 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
145 struct Block_literal {
146 /// Initialized to one of:
147 /// extern void *_NSConcreteStackBlock[];
148 /// extern void *_NSConcreteGlobalBlock[];
149 ///
150 /// In theory, we could start one off malloc'ed by setting
151 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
152 /// this isa:
153 /// extern void *_NSConcreteMallocBlock[];
154 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000155
John McCall351762c2011-02-07 10:33:21 +0000156 /// These are the flags (with corresponding bit number) that the
157 /// compiler is actually supposed to know about.
158 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
159 /// descriptor provides copy and dispose helper functions
160 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
161 /// object with a nontrivial destructor or copy constructor
162 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
163 /// as global memory
164 /// 29. BLOCK_USE_STRET - indicates that the block function
165 /// uses stret, which objc_msgSend needs to know about
166 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
167 /// @encoded signature string
168 /// And we're not supposed to manipulate these:
169 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
170 /// to malloc'ed memory
171 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
172 /// to GC-allocated memory
173 /// Additionally, the bottom 16 bits are a reference count which
174 /// should be zero on the stack.
175 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000176
John McCall351762c2011-02-07 10:33:21 +0000177 /// Reserved; should be zero-initialized.
178 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000179
John McCall351762c2011-02-07 10:33:21 +0000180 /// Function pointer generated from block literal.
181 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000182
John McCall351762c2011-02-07 10:33:21 +0000183 /// Block description metadata generated from block literal.
184 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000185
John McCall351762c2011-02-07 10:33:21 +0000186 /// Captured values follow.
187 _CapturesTypes captures...;
188 };
189 */
David Chisnall950a9512009-11-17 19:33:30 +0000190
John McCall351762c2011-02-07 10:33:21 +0000191/// The number of fields in a block header.
192const unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000193
John McCall351762c2011-02-07 10:33:21 +0000194namespace {
195 /// A chunk of data that we actually have to capture in the block.
196 struct BlockLayoutChunk {
197 CharUnits Alignment;
198 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; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000201 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000202 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000203
John McCall351762c2011-02-07 10:33:21 +0000204 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000205 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000206 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000207 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000208 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000209 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000210
John McCall351762c2011-02-07 10:33:21 +0000211 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000212 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
213 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000214 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000215 info.CXXThisOffset = offset;
216 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000217 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
218 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000219 }
John McCall87fe5d52010-05-20 01:18:31 +0000220 }
John McCall351762c2011-02-07 10:33:21 +0000221 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000222
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000223 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
224 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000225 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000226 if (left.Alignment != right.Alignment)
227 return left.Alignment > right.Alignment;
228
229 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000230 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000231 return 1;
232 if (chunk.Lifetime == Qualifiers::OCL_Strong)
233 return 0;
234 if (chunk.Lifetime == Qualifiers::OCL_Weak)
235 return 2;
236 return 3;
237 };
238
239 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000240 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000241} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000242
John McCallb0a3ecb2011-02-08 03:07:00 +0000243/// Determines if the given type is safe for constant capture in C++.
244static bool isSafeForCXXConstantCapture(QualType type) {
245 const RecordType *recordType =
246 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
247
248 // Only records can be unsafe.
249 if (!recordType) return true;
250
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000251 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000252
253 // Maintain semantics for classes with non-trivial dtors or copy ctors.
254 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000255 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000256
257 // Otherwise, we just have to make sure there aren't any mutable
258 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000259 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000260}
261
John McCall351762c2011-02-07 10:33:21 +0000262/// It is illegal to modify a const object after initialization.
263/// Therefore, if a const object has a constant initializer, we don't
264/// actually need to keep storage for it in the block; we'll just
265/// rematerialize it at the start of the block function. This is
266/// acceptable because we make no promises about address stability of
267/// captured variables.
268static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000269 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000270 const VarDecl *var) {
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000271 // Return if this is a function paramter. We shouldn't try to
272 // rematerialize default arguments of function parameters.
273 if (isa<ParmVarDecl>(var))
274 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000275
John McCall351762c2011-02-07 10:33:21 +0000276 QualType type = var->getType();
277
278 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000279 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000280
John McCallb0a3ecb2011-02-08 03:07:00 +0000281 // Furthermore, in C++ we have to worry about mutable fields:
282 // C++ [dcl.type.cv]p4:
283 // Except that any class member declared mutable can be
284 // modified, any attempt to modify a const object during its
285 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000286 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000287 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000288
289 // If the variable doesn't have any initializer (shouldn't this be
290 // invalid?), it's not clear what we should do. Maybe capture as
291 // zero?
292 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000293 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000294
Richard Smithdafff942012-01-14 04:30:29 +0000295 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000296}
297
298/// Get the low bit of a nonzero character count. This is the
299/// alignment of the nth byte if the 0th byte is universally aligned.
300static CharUnits getLowBit(CharUnits v) {
301 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
302}
303
304static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000306 // The header is basically 'struct { void *; int; int; void *; void *; }'.
307 // Assert that that struct is packed.
308 assert(CGM.getIntSize() <= CGM.getPointerSize());
309 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
310 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000311
John McCall7f416cc2015-09-08 08:05:57 +0000312 info.BlockAlign = CGM.getPointerAlign();
313 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000314
315 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000316 elementTypes.push_back(CGM.VoidPtrTy);
317 elementTypes.push_back(CGM.IntTy);
318 elementTypes.push_back(CGM.IntTy);
319 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000320 elementTypes.push_back(CGM.getBlockDescriptorType());
321
322 assert(elementTypes.size() == BlockHeaderSize);
323}
324
325/// Compute the layout of the given block. Attempts to lay the block
326/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000327static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
328 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000329 ASTContext &C = CGM.getContext();
330 const BlockDecl *block = info.getBlockDecl();
331
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000333 initializeForBlockHeader(CGM, info, elementTypes);
334
335 if (!block->hasCaptures()) {
336 info.StructureType =
337 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
338 info.CanBeGlobal = true;
339 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000340 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000341 else if (C.getLangOpts().ObjC1 &&
342 CGM.getLangOpts().getGC() == LangOptions::NonGC)
343 info.HasCapturedVariableLayout = true;
344
John McCall351762c2011-02-07 10:33:21 +0000345 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000346 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000347 layout.reserve(block->capturesCXXThis() +
348 (block->capture_end() - block->capture_begin()));
349
350 CharUnits maxFieldAlign;
351
352 // First, 'this'.
353 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000354 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
355 "Can't capture 'this' outside a method");
356 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000357
John McCall7f416cc2015-09-08 08:05:57 +0000358 // Theoretically, this could be in a different address space, so
359 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000360 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000361 std::pair<CharUnits,CharUnits> tinfo
362 = CGM.getContext().getTypeInfoInChars(thisType);
363 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
364
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000365 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
366 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000367 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000368 }
369
370 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000371 for (const auto &CI : block->captures()) {
372 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000373
Aaron Ballman9371dd22014-03-14 18:34:04 +0000374 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000375 // We have to copy/dispose of the __block reference.
376 info.NeedsCopyDispose = true;
377
John McCall351762c2011-02-07 10:33:21 +0000378 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000379 CharUnits align = CGM.getPointerAlign();
380 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000381
John McCall7f416cc2015-09-08 08:05:57 +0000382 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
383 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000384 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000385 continue;
386 }
387
388 // Otherwise, build a layout chunk with the size and alignment of
389 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000390 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000391 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
392 continue;
393 }
394
John McCall31168b02011-06-15 23:02:42 +0000395 // If we have a lifetime qualifier, honor it for capture purposes.
396 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000397 Qualifiers::ObjCLifetime lifetime =
398 variable->getType().getObjCLifetime();
399 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000400 switch (lifetime) {
401 case Qualifiers::OCL_None: llvm_unreachable("impossible");
402 case Qualifiers::OCL_ExplicitNone:
403 case Qualifiers::OCL_Autoreleasing:
404 break;
John McCall351762c2011-02-07 10:33:21 +0000405
John McCall31168b02011-06-15 23:02:42 +0000406 case Qualifiers::OCL_Strong:
407 case Qualifiers::OCL_Weak:
408 info.NeedsCopyDispose = true;
409 }
410
411 // Block pointers require copy/dispose. So do Objective-C pointers.
412 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000413 // But honor the inert __unsafe_unretained qualifier, which doesn't
414 // actually make it into the type system.
415 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
416 lifetime = Qualifiers::OCL_ExplicitNone;
417 } else {
418 info.NeedsCopyDispose = true;
419 // used for mrr below.
420 lifetime = Qualifiers::OCL_Strong;
421 }
John McCall351762c2011-02-07 10:33:21 +0000422
423 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000424 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000425 info.NeedsCopyDispose = true;
426 info.HasCXXObject = true;
427
428 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000429 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000430 if (const CXXRecordDecl *record =
431 variable->getType()->getAsCXXRecordDecl()) {
432 if (!record->hasTrivialDestructor()) {
433 info.HasCXXObject = true;
434 info.NeedsCopyDispose = true;
435 }
436 }
437 }
438
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000439 QualType VT = variable->getType();
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000440
441 // If the variable is captured by an enclosing block or lambda expression,
442 // use the type of the capture field.
443 if (CGF->BlockInfo && CI.isNested())
444 VT = CGF->BlockInfo->getCapture(variable).fieldType();
445 else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
446 VT = FD->getType();
447
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000448 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000449 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000450
John McCall351762c2011-02-07 10:33:21 +0000451 maxFieldAlign = std::max(maxFieldAlign, align);
452
Jay Foad7c57be32011-07-11 09:56:20 +0000453 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000454 CGM.getTypes().ConvertTypeForMem(VT);
455
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000456 layout.push_back(
457 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000458 }
459
460 // If that was everything, we're done here.
461 if (layout.empty()) {
462 info.StructureType =
463 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
464 info.CanBeGlobal = true;
465 return;
466 }
467
468 // Sort the layout by alignment. We have to use a stable sort here
469 // to get reproducible results. There should probably be an
470 // llvm::array_pod_stable_sort.
471 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000472
473 // Needed for blocks layout info.
474 info.BlockHeaderForcedGapOffset = info.BlockSize;
475 info.BlockHeaderForcedGapSize = CharUnits::Zero();
476
John McCall351762c2011-02-07 10:33:21 +0000477 CharUnits &blockSize = info.BlockSize;
478 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
479
480 // Assuming that the first byte in the header is maximally aligned,
481 // get the alignment of the first byte following the header.
482 CharUnits endAlign = getLowBit(blockSize);
483
484 // If the end of the header isn't satisfactorily aligned for the
485 // maximum thing, look for things that are okay with the header-end
486 // alignment, and keep appending them until we get something that's
487 // aligned right. This algorithm is only guaranteed optimal if
488 // that condition is satisfied at some point; otherwise we can get
489 // things like:
490 // header // next byte has alignment 4
491 // something_with_size_5; // next byte has alignment 1
492 // something_with_alignment_8;
493 // which has 7 bytes of padding, as opposed to the naive solution
494 // which might have less (?).
495 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000497 li = layout.begin() + 1, le = layout.end();
498
499 // Look for something that the header end is already
500 // satisfactorily aligned for.
501 for (; li != le && endAlign < li->Alignment; ++li)
502 ;
503
504 // If we found something that's naturally aligned for the end of
505 // the header, keep adding things...
506 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000508 for (; li != le; ++li) {
509 assert(endAlign >= li->Alignment);
510
John McCall7f416cc2015-09-08 08:05:57 +0000511 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000512 elementTypes.push_back(li->Type);
513 blockSize += li->Size;
514 endAlign = getLowBit(blockSize);
515
516 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000517 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000518 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000519 }
John McCall351762c2011-02-07 10:33:21 +0000520 }
John McCall351762c2011-02-07 10:33:21 +0000521 // Don't re-append everything we just appended.
522 layout.erase(first, li);
523 }
524 }
525
John McCallac0350a2012-04-26 21:14:42 +0000526 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000527
John McCall351762c2011-02-07 10:33:21 +0000528 // At this point, we just have to add padding if the end align still
529 // isn't aligned right.
530 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000531 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000532 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000533
John McCall7f416cc2015-09-08 08:05:57 +0000534 // If we haven't yet added any fields, remember that there was an
535 // initial gap; this need to go into the block layout bit map.
536 if (blockSize == info.BlockHeaderForcedGapOffset) {
537 info.BlockHeaderForcedGapSize = padding;
538 }
539
John McCalle3dc1702011-02-15 09:22:45 +0000540 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
541 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000542 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000543 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000544 }
545
John McCall1db0a2f2012-05-01 20:28:00 +0000546 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000547 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000548 // Slam everything else on now. This works because they have
549 // strictly decreasing alignment and we expect that size is always a
550 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000551 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000552 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000553 if (endAlign < li->Alignment) {
554 // size may not be multiple of alignment. This can only happen with
555 // an over-aligned variable. We will be adding a padding field to
556 // make the size be multiple of alignment.
557 CharUnits padding = li->Alignment - endAlign;
558 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
559 padding.getQuantity()));
560 blockSize += padding;
561 endAlign = getLowBit(blockSize);
562 }
John McCall351762c2011-02-07 10:33:21 +0000563 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000564 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000565 elementTypes.push_back(li->Type);
566 blockSize += li->Size;
567 endAlign = getLowBit(blockSize);
568 }
569
570 info.StructureType =
571 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
572}
573
John McCall08ef4662011-11-10 08:15:53 +0000574/// Enter the scope of a block. This should be run at the entrance to
575/// a full-expression so that the block's cleanups are pushed at the
576/// right place in the stack.
577static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000578 assert(CGF.HaveInsertPoint());
579
John McCall08ef4662011-11-10 08:15:53 +0000580 // Allocate the block info and place it at the head of the list.
581 CGBlockInfo &blockInfo =
582 *new CGBlockInfo(block, CGF.CurFn->getName());
583 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
584 CGF.FirstBlockInfo = &blockInfo;
585
586 // Compute information about the layout, etc., of this block,
587 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000588 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000589
590 // Nothing else to do if it can be global.
591 if (blockInfo.CanBeGlobal) return;
592
593 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000594 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
595 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000596
597 // If there are cleanups to emit, enter them (but inactive).
598 if (!blockInfo.NeedsCopyDispose) return;
599
600 // Walk through the captures (in order) and find the ones not
601 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000602 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000603 // Ignore __block captures; there's nothing special in the
604 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000605 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000606
607 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000608 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000609 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
610 if (capture.isConstant()) continue;
611
612 // Ignore objects that aren't destructed.
613 QualType::DestructionKind dtorKind =
614 variable->getType().isDestructedType();
615 if (dtorKind == QualType::DK_none) continue;
616
617 CodeGenFunction::Destroyer *destroyer;
618
619 // Block captures count as local values and have imprecise semantics.
620 // They also can't be arrays, so need to worry about that.
621 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000622 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000623 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000624 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000625 }
626
627 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000628 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
629 capture.getIndex(),
630 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000631
John McCallf4beacd2011-11-10 10:43:54 +0000632 // We can use that GEP as the dominating IP.
633 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000634 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000635
John McCall08ef4662011-11-10 08:15:53 +0000636 CleanupKind cleanupKind = InactiveNormalCleanup;
637 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
638 if (useArrayEHCleanup)
639 cleanupKind = InactiveNormalAndEHCleanup;
640
641 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000642 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000643
644 // Remember where that cleanup was.
645 capture.setCleanup(CGF.EHStack.stable_begin());
646 }
647}
648
649/// Enter a full-expression with a non-trivial number of objects to
650/// clean up. This is in this file because, at the moment, the only
651/// kind of cleanup object is a BlockDecl*.
652void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
653 assert(E->getNumObjects() != 0);
654 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
655 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
656 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
657 enterBlockScope(*this, *i);
658 }
659}
660
661/// Find the layout for the given block in a linked list and remove it.
662static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
663 const BlockDecl *block) {
664 while (true) {
665 assert(head && *head);
666 CGBlockInfo *cur = *head;
667
668 // If this is the block we're looking for, splice it out of the list.
669 if (cur->getBlockDecl() == block) {
670 *head = cur->NextBlockInfo;
671 return cur;
672 }
673
674 head = &cur->NextBlockInfo;
675 }
676}
677
678/// Destroy a chain of block layouts.
679void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
680 assert(head && "destroying an empty chain");
681 do {
682 CGBlockInfo *cur = head;
683 head = cur->NextBlockInfo;
684 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000685 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000686}
687
John McCall351762c2011-02-07 10:33:21 +0000688/// Emit a block literal expression in the current function.
689llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000690 // If the block has no captures, we won't have a pre-computed
691 // layout for it.
692 if (!blockExpr->getBlockDecl()->hasCaptures()) {
693 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000694 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000695 blockInfo.BlockExpression = blockExpr;
696 return EmitBlockLiteral(blockInfo);
697 }
John McCall351762c2011-02-07 10:33:21 +0000698
John McCall08ef4662011-11-10 08:15:53 +0000699 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000700 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000701 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
702 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000703
John McCall08ef4662011-11-10 08:15:53 +0000704 blockInfo->BlockExpression = blockExpr;
705 return EmitBlockLiteral(*blockInfo);
706}
707
708llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
709 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000710 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000711 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000712 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000713 LocalDeclMap,
714 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000715 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000716
717 // If there is nothing to capture, we can emit this as a global block.
718 if (blockInfo.CanBeGlobal)
719 return buildGlobalBlock(CGM, blockInfo, blockFn);
720
721 // Otherwise, we have to emit this as a local block.
722
723 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000724 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000725
726 // Build the block descriptor.
727 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
728
John McCall7f416cc2015-09-08 08:05:57 +0000729 Address blockAddr = blockInfo.LocalAddress;
730 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000731
732 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000733 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000734 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000735 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
736 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000737 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000738
John McCall7f416cc2015-09-08 08:05:57 +0000739 auto projectField =
740 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
741 return Builder.CreateStructGEP(blockAddr, index, offset, name);
742 };
743 auto storeField =
744 [&](llvm::Value *value, unsigned index, CharUnits offset,
745 const Twine &name) {
746 Builder.CreateStore(value, projectField(index, offset, name));
747 };
748
749 // Initialize the block header.
750 {
751 // We assume all the header fields are densely packed.
752 unsigned index = 0;
753 CharUnits offset;
754 auto addHeaderField =
755 [&](llvm::Value *value, CharUnits size, const Twine &name) {
756 storeField(value, index, offset, name);
757 offset += size;
758 index++;
759 };
760
761 addHeaderField(isa, getPointerSize(), "block.isa");
762 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
763 getIntSize(), "block.flags");
764 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
765 getIntSize(), "block.reserved");
766 addHeaderField(blockFn, getPointerSize(), "block.invoke");
767 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
768 }
John McCall351762c2011-02-07 10:33:21 +0000769
770 // Finally, capture all the values into the block.
771 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
772
773 // First, 'this'.
774 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
776 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000777 Builder.CreateStore(LoadCXXThis(), addr);
778 }
779
780 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000781 for (const auto &CI : blockDecl->captures()) {
782 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000783 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
784
785 // Ignore constant captures.
786 if (capture.isConstant()) continue;
787
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000788 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000789
790 // This will be a [[type]]*, except that a byref entry will just be
791 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000792 Address blockField =
793 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000794
795 // Compute the address of the thing we're going to move into the
796 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000797 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000798
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000799 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000800 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000801 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000802 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000803 } else if (CI.isByRef()) {
804 if (BlockInfo && CI.isNested()) {
805 // We need to use the capture from the enclosing block.
806 const CGBlockInfo::Capture &enclosingCapture =
807 BlockInfo->getCapture(variable);
808
809 // This is a [[type]]*, except that a byref entry wil just be an i8**.
810 src = Builder.CreateStructGEP(LoadBlockStruct(),
811 enclosingCapture.getIndex(),
812 enclosingCapture.getOffset(),
813 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000814 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000815 auto I = LocalDeclMap.find(variable);
816 assert(I != LocalDeclMap.end());
817 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000818 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000819 } else {
820 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
821 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
822 type.getNonReferenceType(), VK_LValue,
823 SourceLocation());
824 src = EmitDeclRefLValue(&declRef).getAddress();
825 };
John McCall351762c2011-02-07 10:33:21 +0000826
827 // For byrefs, we just write the pointer to the byref struct into
828 // the block field. There's no need to chase the forwarding
829 // pointer at this point, since we're building something that will
830 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000831 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000832 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000833 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000834 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000835 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000836 else
John McCall7f416cc2015-09-08 08:05:57 +0000837 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000838
John McCalle3dc1702011-02-15 09:22:45 +0000839 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000840 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000841
842 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000843 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000844 if (blockDecl->isConversionFromLambda()) {
845 // If we have a lambda conversion, emit the expression
846 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000847 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000848 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000849 AggValueSlot::IsDestructed,
850 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000851 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000852 EmitAggExpr(copyExpr, Slot);
853 } else {
854 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
855 }
John McCall351762c2011-02-07 10:33:21 +0000856
857 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000858 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000859 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000860
861 // If this is an ARC __strong block-pointer variable, don't do a
862 // block copy.
863 //
864 // TODO: this can be generalized into the normal initialization logic:
865 // we should never need to do a block-copy when initializing a local
866 // variable, because the local variable's lifetime should be strictly
867 // contained within the stack block's.
868 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
869 type->isBlockPointerType()) {
870 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000871 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000872 value = EmitARCRetainNonBlock(value);
873
874 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000875 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000876
877 // Otherwise, fake up a POD copy into the block field.
878 } else {
John McCall31168b02011-06-15 23:02:42 +0000879 // Fake up a new variable so that EmitScalarInit doesn't think
880 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000881 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
882 SourceLocation(), /*name*/ nullptr,
883 type);
John McCall31168b02011-06-15 23:02:42 +0000884
John McCall93be3f72011-02-07 18:37:40 +0000885 // We use one of these or the other depending on whether the
886 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000887 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
888 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
889 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000890
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000891 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000892 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000893 // FIXME: Pass a specific location for the expr init so that the store is
894 // attributed to a reasonable location - otherwise it may be attributed to
895 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000896 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000897 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000898 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000899 }
900
John McCall08ef4662011-11-10 08:15:53 +0000901 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000902 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000903 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
904 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000905 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000906 }
John McCall351762c2011-02-07 10:33:21 +0000907 }
908
909 // Cast to the converted block-pointer type, which happens (somewhat
910 // unfortunately) to be a pointer to function type.
911 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000912 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000913 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000914
John McCall351762c2011-02-07 10:33:21 +0000915 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000916}
917
918
Chris Lattnera5f58b02011-07-09 17:41:47 +0000919llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000920 if (BlockDescriptorType)
921 return BlockDescriptorType;
922
Chris Lattnera5f58b02011-07-09 17:41:47 +0000923 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000924 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000925
Mike Stump650c9322009-02-13 15:16:56 +0000926 // struct __block_descriptor {
927 // unsigned long reserved;
928 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000929 //
930 // // later, the following will be added
931 //
932 // struct {
933 // void (*copyHelper)();
934 // void (*copyHelper)();
935 // } helpers; // !!! optional
936 //
937 // const char *signature; // the block signature
938 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000939 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000940 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000941 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000942 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000943
John McCall351762c2011-02-07 10:33:21 +0000944 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +0000945 unsigned AddrSpace = 0;
946 if (getLangOpts().OpenCL)
947 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
948 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +0000949 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000950}
951
Chris Lattnera5f58b02011-07-09 17:41:47 +0000952llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000953 if (GenericBlockLiteralType)
954 return GenericBlockLiteralType;
955
Chris Lattnera5f58b02011-07-09 17:41:47 +0000956 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000957
Mike Stump005c9a62009-02-13 15:25:34 +0000958 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000959 // void *__isa;
960 // int __flags;
961 // int __reserved;
962 // void (*__invoke)(void *);
963 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000964 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000965 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000966 llvm::StructType::create("struct.__block_literal_generic",
967 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000968 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000969
Mike Stump005c9a62009-02-13 15:25:34 +0000970 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000971}
972
Nick Lewycky2d84e842013-10-02 02:29:49 +0000973RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000974 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000975 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000976 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000977
John McCallb92ab1a2016-10-26 23:46:34 +0000978 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000979
980 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000981 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000982 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000983
984 // Bitcast the callee to a block literal.
John McCallb92ab1a2016-10-26 23:46:34 +0000985 BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000986
987 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000988 llvm::Value *FuncPtr =
John McCallb92ab1a2016-10-26 23:46:34 +0000989 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000990
John McCallb92ab1a2016-10-26 23:46:34 +0000991 BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000992
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000993 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000994 CallArgList Args;
John McCallb92ab1a2016-10-26 23:46:34 +0000995 Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000996
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000997 QualType FnType = BPT->getPointeeType();
998
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000999 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001000 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001001
Anders Carlsson5f50c652009-04-07 22:10:22 +00001002 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001003 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001004
John McCall85915252011-03-09 08:39:33 +00001005 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001006 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001007 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001008
Anders Carlsson5f50c652009-04-07 22:10:22 +00001009 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001010 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001011
Chris Lattner2192fe52011-07-18 04:24:23 +00001012 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +00001013 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001014
John McCallb92ab1a2016-10-26 23:46:34 +00001015 // Prepare the callee.
1016 CGCallee Callee(CGCalleeInfo(), Func);
1017
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001018 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001019 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001020}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001021
John McCall7f416cc2015-09-08 08:05:57 +00001022Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1023 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001024 assert(BlockInfo && "evaluating block ref without block information?");
1025 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001026
John McCall351762c2011-02-07 10:33:21 +00001027 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001028 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001029
John McCall7f416cc2015-09-08 08:05:57 +00001030 Address addr =
1031 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1032 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001033
John McCall351762c2011-02-07 10:33:21 +00001034 if (isByRef) {
1035 // addr should be a void** right now. Load, then cast the result
1036 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001037
John McCall7f416cc2015-09-08 08:05:57 +00001038 auto &byrefInfo = getBlockByrefInfo(variable);
1039 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001040
John McCall7f416cc2015-09-08 08:05:57 +00001041 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1042 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001043
John McCall7f416cc2015-09-08 08:05:57 +00001044 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1045 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001046 }
1047
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001048 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001049 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001050
John McCall351762c2011-02-07 10:33:21 +00001051 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001052}
1053
Mike Stump2d5a2872009-02-14 22:16:35 +00001054llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001055CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001056 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001057 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1058 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001059
John McCall351762c2011-02-07 10:33:21 +00001060 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001061 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001062
John McCall351762c2011-02-07 10:33:21 +00001063 // Using that metadata, generate the actual block function.
1064 llvm::Constant *blockFn;
1065 {
John McCall7f416cc2015-09-08 08:05:57 +00001066 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001067 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1068 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001069 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001070 false);
John McCall351762c2011-02-07 10:33:21 +00001071 }
John McCalle3dc1702011-02-15 09:22:45 +00001072 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001073
John McCallad7c5c12011-02-08 08:22:06 +00001074 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001075}
1076
John McCall351762c2011-02-07 10:33:21 +00001077static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1078 const CGBlockInfo &blockInfo,
1079 llvm::Constant *blockFn) {
1080 assert(blockInfo.CanBeGlobal);
1081
1082 // Generate the constants for the block literal initializer.
1083 llvm::Constant *fields[BlockHeaderSize];
1084
1085 // isa
1086 fields[0] = CGM.getNSConcreteGlobalBlock();
1087
1088 // __flags
John McCall85915252011-03-09 08:39:33 +00001089 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1090 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1091
John McCalle3dc1702011-02-15 09:22:45 +00001092 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001093
1094 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001095 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001096
1097 // Function
1098 fields[3] = blockFn;
1099
1100 // Descriptor
1101 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1102
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001103 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001104
1105 llvm::GlobalVariable *literal =
1106 new llvm::GlobalVariable(CGM.getModule(),
1107 init->getType(),
1108 /*constant*/ true,
1109 llvm::GlobalVariable::InternalLinkage,
1110 init,
1111 "__block_literal_global");
1112 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1113
1114 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001115 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001116 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1117 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001118}
1119
John McCall7f416cc2015-09-08 08:05:57 +00001120void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1121 unsigned argNum,
1122 llvm::Value *arg) {
1123 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1124
1125 llvm::Value *localAddr = nullptr;
1126 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1127 // Allocate a stack slot to let the debug info survive the RA.
1128 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1129 Builder.CreateStore(arg, alloc);
1130 localAddr = Builder.CreateLoad(alloc);
1131 }
1132
1133 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001134 if (CGM.getCodeGenOpts().getDebugInfo() >=
1135 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001136 DI->setLocation(D->getLocation());
1137 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1138 localAddr, Builder);
1139 }
1140 }
1141
1142 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1143 ApplyDebugLocation Scope(*this, StartLoc);
1144
1145 // Instead of messing around with LocalDeclMap, just set the value
1146 // directly as BlockPointer.
1147 BlockPointer = Builder.CreateBitCast(arg,
1148 BlockInfo->StructureType->getPointerTo(),
1149 "block");
1150}
1151
1152Address CodeGenFunction::LoadBlockStruct() {
1153 assert(BlockInfo && "not in a block invocation function!");
1154 assert(BlockPointer && "no block pointer set!");
1155 return Address(BlockPointer, BlockInfo->BlockAlign);
1156}
1157
Mike Stump4446dcf2009-03-05 08:32:30 +00001158llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001159CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1160 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001161 const DeclMapTy &ldm,
1162 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001163 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001164
Fariborz Jahanian63628032012-06-26 16:06:38 +00001165 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001166
1167 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001168
John McCall351762c2011-02-07 10:33:21 +00001169 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001170
Mike Stump5469f292009-03-13 23:34:28 +00001171 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001172 // to be local to this function as well, in case they're directly
1173 // referenced in a block.
1174 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001175 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001176 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001177 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001178 }
1179
John McCall351762c2011-02-07 10:33:21 +00001180 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001181
John McCall351762c2011-02-07 10:33:21 +00001182 // Build the argument list.
1183 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001184
John McCall351762c2011-02-07 10:33:21 +00001185 // The first argument is the block pointer. Just take it as a void*
1186 // and cast it later.
1187 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001188 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001189
Richard Smith053f6c62014-05-16 23:01:30 +00001190 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001191 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001192 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001193
John McCall351762c2011-02-07 10:33:21 +00001194 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001195 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001196
John McCall351762c2011-02-07 10:33:21 +00001197 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001198 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001199 const CGFunctionInfo &fnInfo =
1200 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001201 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001202 blockInfo.UsesStret = true;
1203
John McCalla729c622012-02-17 03:33:10 +00001204 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001205
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001206 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001207 llvm::Function *fn = llvm::Function::Create(
1208 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001209 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001210
John McCall351762c2011-02-07 10:33:21 +00001211 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001212 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001213 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001214 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001215
John McCall147d0212011-02-22 22:38:33 +00001216 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001217
Adrian Prantl0f6df002013-03-29 19:20:35 +00001218 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1219 // won't delete the dbg.declare intrinsics for captured variables.
1220 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1221 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1222 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001223 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1224 getPointerAlign(),
1225 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001226 // Set the DebugLocation to empty, so the store is recognized as a
1227 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001228 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001229 Builder.CreateStore(BlockPointer, Alloca);
1230 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001231 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001232
John McCall87fe5d52010-05-20 01:18:31 +00001233 // If we have a C++ 'this' reference, go ahead and force it into
1234 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001235 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001236 Address addr =
1237 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1238 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001239 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001240 }
1241
John McCall351762c2011-02-07 10:33:21 +00001242 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001243 for (const auto &CI : blockDecl->captures()) {
1244 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001245 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1246 if (!capture.isConstant()) continue;
1247
John McCall7f416cc2015-09-08 08:05:57 +00001248 CharUnits align = getContext().getDeclAlign(variable);
1249 Address alloca =
1250 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001251
John McCall7f416cc2015-09-08 08:05:57 +00001252 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001253
John McCall7f416cc2015-09-08 08:05:57 +00001254 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001255 }
1256
John McCall113bee02012-03-10 09:33:50 +00001257 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001258 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1259 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1260 --entry_ptr;
1261
Eli Friedman2495ab02012-02-25 02:48:22 +00001262 if (IsLambdaConversionToBlock)
1263 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001264 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001265 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001266 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001267 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001268 }
Mike Stump017460a2009-10-01 22:29:41 +00001269
Mike Stump7d699112009-10-01 00:27:30 +00001270 // Remember where we were...
1271 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001272
Mike Stump7d699112009-10-01 00:27:30 +00001273 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001274 ++entry_ptr;
1275 Builder.SetInsertPoint(entry, entry_ptr);
1276
John McCall113bee02012-03-10 09:33:50 +00001277 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001278 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001279 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001280 for (const auto &CI : blockDecl->captures()) {
1281 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001282 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001283
Benjamin Kramer8c305922016-02-02 11:06:51 +00001284 if (CGM.getCodeGenOpts().getDebugInfo() >=
1285 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001286 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1287 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001288 auto addr = LocalDeclMap.find(variable)->second;
1289 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001290 Builder);
1291 continue;
1292 }
John McCall351762c2011-02-07 10:33:21 +00001293
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001294 DI->EmitDeclareOfBlockDeclRefVariable(
1295 variable, BlockPointerDbgLoc, Builder, blockInfo,
1296 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001297 }
Mike Stump2e722b92009-09-30 02:43:10 +00001298 }
Manman Renab08a9a2013-01-04 18:51:35 +00001299 // Recover location if it was changed in the above loop.
1300 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001301 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001302 }
John McCall351762c2011-02-07 10:33:21 +00001303
Mike Stump7d699112009-10-01 00:27:30 +00001304 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001305 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001306 Builder.ClearInsertionPoint();
1307 else
1308 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001309
John McCall351762c2011-02-07 10:33:21 +00001310 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001311
John McCall351762c2011-02-07 10:33:21 +00001312 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001313}
Mike Stump1db7d042009-02-28 09:07:16 +00001314
John McCall351762c2011-02-07 10:33:21 +00001315/*
1316 notes.push_back(HelperInfo());
1317 HelperInfo &note = notes.back();
1318 note.index = capture.getIndex();
1319 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1320 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001321
John McCall351762c2011-02-07 10:33:21 +00001322 if (ci->isByRef()) {
1323 note.flag = BLOCK_FIELD_IS_BYREF;
1324 if (type.isObjCGCWeak())
1325 note.flag |= BLOCK_FIELD_IS_WEAK;
1326 } else if (type->isBlockPointerType()) {
1327 note.flag = BLOCK_FIELD_IS_BLOCK;
1328 } else {
1329 note.flag = BLOCK_FIELD_IS_OBJECT;
1330 }
1331 */
Mike Stump1db7d042009-02-28 09:07:16 +00001332
John McCallf593b102013-01-22 03:56:22 +00001333/// Generate the copy-helper function for a block closure object:
1334/// static void block_copy_helper(block_t *dst, block_t *src);
1335/// The runtime will have previously initialized 'dst' by doing a
1336/// bit-copy of 'src'.
1337///
1338/// Note that this copies an entire block closure object to the heap;
1339/// it should not be confused with a 'byref copy helper', which moves
1340/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001341llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001342CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001343 ASTContext &C = getContext();
1344
1345 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001346 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1347 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001348 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001349 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1350 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001351 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCallc56a8b32016-03-11 04:30:31 +00001353 const CGFunctionInfo &FI =
1354 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001355
John McCall351762c2011-02-07 10:33:21 +00001356 // FIXME: it would be nice if these were mergeable with things with
1357 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001358 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001359
1360 llvm::Function *Fn =
1361 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001362 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001363
1364 IdentifierInfo *II
1365 = &CGM.getContext().Idents.get("__copy_helper_block_");
1366
John McCall351762c2011-02-07 10:33:21 +00001367 FunctionDecl *FD = FunctionDecl::Create(C,
1368 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001369 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001370 SourceLocation(), II, C.VoidTy,
1371 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001372 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001373 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001374
1375 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1376
Adrian Prantl95b24e92015-02-03 20:00:54 +00001377 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001378 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001379 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001380 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001381 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001382
John McCall7f416cc2015-09-08 08:05:57 +00001383 Address src = GetAddrOfLocalVar(&srcDecl);
1384 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001385 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001386
John McCall7f416cc2015-09-08 08:05:57 +00001387 Address dst = GetAddrOfLocalVar(&dstDecl);
1388 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001389 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001390
John McCall351762c2011-02-07 10:33:21 +00001391 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001392
Aaron Ballman9371dd22014-03-14 18:34:04 +00001393 for (const auto &CI : blockDecl->captures()) {
1394 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001395 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001396
John McCall351762c2011-02-07 10:33:21 +00001397 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1398 if (capture.isConstant()) continue;
1399
Aaron Ballman9371dd22014-03-14 18:34:04 +00001400 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001401 BlockFieldFlags flags;
1402
John McCalle68b8f42012-10-17 02:28:37 +00001403 bool useARCWeakCopy = false;
1404 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001405
1406 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001407 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001408 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001409
Aaron Ballman9371dd22014-03-14 18:34:04 +00001410 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001411 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001412 if (type.isObjCGCWeak())
1413 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001414
John McCall31168b02011-06-15 23:02:42 +00001415 } else if (type->isObjCRetainableType()) {
1416 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001417 bool isBlockPointer = type->isBlockPointerType();
1418 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001419 flags = BLOCK_FIELD_IS_BLOCK;
1420
1421 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001422 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001423
John McCall460ce582015-10-22 18:38:17 +00001424 // We need to register __weak direct captures with the runtime.
1425 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1426 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001427
John McCall460ce582015-10-22 18:38:17 +00001428 // We need to retain the copied value for __strong direct captures.
1429 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1430 // If it's a block pointer, we have to copy the block and
1431 // assign that to the destination pointer, so we might as
1432 // well use _Block_object_assign. Otherwise we can avoid that.
1433 if (!isBlockPointer)
1434 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001435
1436 // Non-ARC captures of retainable pointers are strong and
1437 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001438 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001439 // fall through
John McCall460ce582015-10-22 18:38:17 +00001440
1441 // Otherwise the memcpy is fine.
1442 } else {
1443 continue;
John McCall31168b02011-06-15 23:02:42 +00001444 }
John McCall460ce582015-10-22 18:38:17 +00001445
1446 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001447 } else {
1448 continue;
1449 }
John McCall351762c2011-02-07 10:33:21 +00001450
1451 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001452 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1453 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001454
1455 // If there's an explicit copy expression, we do that.
1456 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001457 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001458 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001459 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001460 } else {
1461 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001462 if (useARCStrongCopy) {
1463 // At -O0, store null into the destination field (so that the
1464 // storeStrong doesn't over-release) and then call storeStrong.
1465 // This is a workaround to not having an initStrong call.
1466 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001467 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001468 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1469 Builder.CreateStore(null, dstField);
1470 EmitARCStoreStrongCall(dstField, srcValue, true);
1471
1472 // With optimization enabled, take advantage of the fact that
1473 // the blocks runtime guarantees a memcpy of the block data, and
1474 // just emit a retain of the src field.
1475 } else {
1476 EmitARCRetainNonBlock(srcValue);
1477
1478 // We don't need this anymore, so kill it. It's not quite
1479 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001480 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001481 }
1482 } else {
1483 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001484 llvm::Value *dstAddr =
1485 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001486 llvm::Value *args[] = {
1487 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1488 };
1489
1490 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001491 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001492 const Expr *copyExpr =
1493 CGM.getContext().getBlockVarCopyInits(variable);
1494 if (copyExpr) {
1495 copyCanThrow = true; // FIXME: reuse the noexcept logic
1496 }
1497 }
1498
1499 if (copyCanThrow) {
1500 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1501 } else {
1502 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1503 }
John McCalle68b8f42012-10-17 02:28:37 +00001504 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001505 }
1506 }
1507
John McCallad7c5c12011-02-08 08:22:06 +00001508 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001509
John McCalle3dc1702011-02-15 09:22:45 +00001510 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001511}
1512
John McCallf593b102013-01-22 03:56:22 +00001513/// Generate the destroy-helper function for a block closure object:
1514/// static void block_destroy_helper(block_t *theBlock);
1515///
1516/// Note that this destroys a heap-allocated block closure object;
1517/// it should not be confused with a 'byref destroy helper', which
1518/// destroys the heap-allocated contents of an individual __block
1519/// variable.
John McCall351762c2011-02-07 10:33:21 +00001520llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001521CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001522 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001523
John McCall351762c2011-02-07 10:33:21 +00001524 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001525 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1526 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001527 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001528
John McCallc56a8b32016-03-11 04:30:31 +00001529 const CGFunctionInfo &FI =
1530 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001531
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001532 // FIXME: We'd like to put these into a mergable by content, with
1533 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001534 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001535
1536 llvm::Function *Fn =
1537 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001538 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001539
1540 IdentifierInfo *II
1541 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1542
John McCall351762c2011-02-07 10:33:21 +00001543 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001544 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001545 SourceLocation(), II, C.VoidTy,
1546 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001547 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001548
1549 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1550
Adrian Prantl49a78562013-07-24 20:34:39 +00001551 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001552 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001553 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001554 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001555
Chris Lattner2192fe52011-07-18 04:24:23 +00001556 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001557
John McCall7f416cc2015-09-08 08:05:57 +00001558 Address src = GetAddrOfLocalVar(&srcDecl);
1559 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001560 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001561
John McCall351762c2011-02-07 10:33:21 +00001562 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1563
John McCallad7c5c12011-02-08 08:22:06 +00001564 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001565
Aaron Ballman9371dd22014-03-14 18:34:04 +00001566 for (const auto &CI : blockDecl->captures()) {
1567 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001568 QualType type = variable->getType();
1569
1570 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1571 if (capture.isConstant()) continue;
1572
John McCallad7c5c12011-02-08 08:22:06 +00001573 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001574 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001575
John McCalle68b8f42012-10-17 02:28:37 +00001576 bool useARCWeakDestroy = false;
1577 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001578
Aaron Ballman9371dd22014-03-14 18:34:04 +00001579 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001580 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001581 if (type.isObjCGCWeak())
1582 flags |= BLOCK_FIELD_IS_WEAK;
1583 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1584 if (record->hasTrivialDestructor())
1585 continue;
1586 dtor = record->getDestructor();
1587 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001588 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001589 if (type->isBlockPointerType())
1590 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001591
John McCall31168b02011-06-15 23:02:42 +00001592 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001593 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001594
John McCall460ce582015-10-22 18:38:17 +00001595 // Use objc_storeStrong for __strong direct captures; the
1596 // dynamic tools really like it when we do this.
1597 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1598 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001599
John McCall460ce582015-10-22 18:38:17 +00001600 // Support __weak direct captures.
1601 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1602 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001603
John McCall460ce582015-10-22 18:38:17 +00001604 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1605 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1606 // fall through
1607
1608 // Otherwise, we have nothing to do.
1609 } else {
1610 continue;
John McCall31168b02011-06-15 23:02:42 +00001611 }
1612 } else {
1613 continue;
1614 }
John McCall351762c2011-02-07 10:33:21 +00001615
John McCall7f416cc2015-09-08 08:05:57 +00001616 Address srcField =
1617 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001618
1619 // If there's an explicit copy expression, we do that.
1620 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001621 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001622
John McCall31168b02011-06-15 23:02:42 +00001623 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001624 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001625 EmitARCDestroyWeak(srcField);
1626
John McCalle68b8f42012-10-17 02:28:37 +00001627 // Destroy strong objects with a call if requested.
1628 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001629 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001630
John McCall351762c2011-02-07 10:33:21 +00001631 // Otherwise we call _Block_object_dispose. It wouldn't be too
1632 // hard to just emit this as a cleanup if we wanted to make sure
1633 // that things were done in reverse.
1634 } else {
1635 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001636 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001637 BuildBlockRelease(value, flags);
1638 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001639 }
1640
John McCall351762c2011-02-07 10:33:21 +00001641 cleanups.ForceCleanup();
1642
John McCallad7c5c12011-02-08 08:22:06 +00001643 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001644
John McCalle3dc1702011-02-15 09:22:45 +00001645 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001646}
1647
John McCallf9b056b2011-03-31 08:03:29 +00001648namespace {
1649
1650/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001651class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001652 BlockFieldFlags Flags;
1653
1654public:
1655 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001656 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001657
John McCall7f416cc2015-09-08 08:05:57 +00001658 void emitCopy(CodeGenFunction &CGF, Address destField,
1659 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001660 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1661
1662 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1663 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1664
1665 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1666
1667 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1668 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001669
John McCall7f416cc2015-09-08 08:05:57 +00001670 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001671 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001672 }
1673
John McCall7f416cc2015-09-08 08:05:57 +00001674 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001675 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1676 llvm::Value *value = CGF.Builder.CreateLoad(field);
1677
1678 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1679 }
1680
Craig Topper4f12f102014-03-12 06:41:41 +00001681 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001682 id.AddInteger(Flags.getBitMask());
1683 }
1684};
1685
John McCall31168b02011-06-15 23:02:42 +00001686/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001687class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001688public:
John McCall7f416cc2015-09-08 08:05:57 +00001689 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 void emitCopy(CodeGenFunction &CGF, Address destField,
1692 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001693 CGF.EmitARCMoveWeak(destField, srcField);
1694 }
1695
John McCall7f416cc2015-09-08 08:05:57 +00001696 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001697 CGF.EmitARCDestroyWeak(field);
1698 }
1699
Craig Topper4f12f102014-03-12 06:41:41 +00001700 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001701 // 0 is distinguishable from all pointers and byref flags
1702 id.AddInteger(0);
1703 }
1704};
1705
1706/// Emits the copy/dispose helpers for an ARC __block __strong variable
1707/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001708class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001709public:
John McCall7f416cc2015-09-08 08:05:57 +00001710 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001711
John McCall7f416cc2015-09-08 08:05:57 +00001712 void emitCopy(CodeGenFunction &CGF, Address destField,
1713 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001714 // Do a "move" by copying the value and then zeroing out the old
1715 // variable.
1716
John McCall7f416cc2015-09-08 08:05:57 +00001717 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001718
John McCall31168b02011-06-15 23:02:42 +00001719 llvm::Value *null =
1720 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001721
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001722 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001723 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001724 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1725 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1726 return;
1727 }
John McCall7f416cc2015-09-08 08:05:57 +00001728 CGF.Builder.CreateStore(value, destField);
1729 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001730 }
1731
John McCall7f416cc2015-09-08 08:05:57 +00001732 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001733 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001734 }
1735
Craig Topper4f12f102014-03-12 06:41:41 +00001736 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001737 // 1 is distinguishable from all pointers and byref flags
1738 id.AddInteger(1);
1739 }
1740};
1741
John McCall3a237aa2011-11-09 03:17:26 +00001742/// Emits the copy/dispose helpers for an ARC __block __strong
1743/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001744class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001745public:
John McCall7f416cc2015-09-08 08:05:57 +00001746 ARCStrongBlockByrefHelpers(CharUnits alignment)
1747 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001748
John McCall7f416cc2015-09-08 08:05:57 +00001749 void emitCopy(CodeGenFunction &CGF, Address destField,
1750 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001751 // Do the copy with objc_retainBlock; that's all that
1752 // _Block_object_assign would do anyway, and we'd have to pass the
1753 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001754 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001755 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001756 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001757 }
1758
John McCall7f416cc2015-09-08 08:05:57 +00001759 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001760 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001761 }
1762
Craig Topper4f12f102014-03-12 06:41:41 +00001763 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001764 // 2 is distinguishable from all pointers and byref flags
1765 id.AddInteger(2);
1766 }
1767};
1768
John McCallf9b056b2011-03-31 08:03:29 +00001769/// Emits the copy/dispose helpers for a __block variable with a
1770/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001771class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001772 QualType VarType;
1773 const Expr *CopyExpr;
1774
1775public:
1776 CXXByrefHelpers(CharUnits alignment, QualType type,
1777 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001778 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001779
Craig Topper8a13c412014-05-21 05:09:00 +00001780 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001781 void emitCopy(CodeGenFunction &CGF, Address destField,
1782 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001783 if (!CopyExpr) return;
1784 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1785 }
1786
John McCall7f416cc2015-09-08 08:05:57 +00001787 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001788 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1789 CGF.PushDestructorCleanup(VarType, field);
1790 CGF.PopCleanupBlocks(cleanupDepth);
1791 }
1792
Craig Topper4f12f102014-03-12 06:41:41 +00001793 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001794 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1795 }
1796};
1797} // end anonymous namespace
1798
1799static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001800generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1801 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001802 ASTContext &Context = CGF.getContext();
1803
1804 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001805
John McCalla738c252011-03-09 04:27:21 +00001806 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001807 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001808 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001809 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001810
Craig Topper8a13c412014-05-21 05:09:00 +00001811 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001812 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001813 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001814
John McCallc56a8b32016-03-11 04:30:31 +00001815 const CGFunctionInfo &FI =
1816 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001817
John McCall7f416cc2015-09-08 08:05:57 +00001818 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001819
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001820 // FIXME: We'd like to put these into a mergable by content, with
1821 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001822 llvm::Function *Fn =
1823 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001824 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001825
1826 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001827 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001828
John McCallf9b056b2011-03-31 08:03:29 +00001829 FunctionDecl *FD = FunctionDecl::Create(Context,
1830 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001831 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001832 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001833 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001834 false, false);
John McCall31168b02011-06-15 23:02:42 +00001835
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001836 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1837
Adrian Prantl22e66b42014-04-11 01:13:04 +00001838 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001839
John McCall7f416cc2015-09-08 08:05:57 +00001840 if (generator.needsCopy()) {
1841 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001842
John McCallf9b056b2011-03-31 08:03:29 +00001843 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001844 Address destField = CGF.GetAddrOfLocalVar(&dst);
1845 destField = Address(CGF.Builder.CreateLoad(destField),
1846 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001847 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001848 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1849 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001850
John McCallf9b056b2011-03-31 08:03:29 +00001851 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001852 Address srcField = CGF.GetAddrOfLocalVar(&src);
1853 srcField = Address(CGF.Builder.CreateLoad(srcField),
1854 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001855 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001856 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1857 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001858
John McCall7f416cc2015-09-08 08:05:57 +00001859 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001860 }
1861
1862 CGF.FinishFunction();
1863
1864 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001865}
1866
John McCallf9b056b2011-03-31 08:03:29 +00001867/// Build the copy helper for a __block variable.
1868static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001869 const BlockByrefInfo &byrefInfo,
1870 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001871 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001872 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001873}
1874
1875/// Generate code for a __block variable's dispose helper.
1876static llvm::Constant *
1877generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001878 const BlockByrefInfo &byrefInfo,
1879 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001880 ASTContext &Context = CGF.getContext();
1881 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001882
John McCalla738c252011-03-09 04:27:21 +00001883 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001884 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001885 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001886 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001887
John McCallc56a8b32016-03-11 04:30:31 +00001888 const CGFunctionInfo &FI =
1889 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001890
John McCall7f416cc2015-09-08 08:05:57 +00001891 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001892
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001893 // FIXME: We'd like to put these into a mergable by content, with
1894 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001895 llvm::Function *Fn =
1896 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001897 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001898 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001899
1900 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001901 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001902
John McCallf9b056b2011-03-31 08:03:29 +00001903 FunctionDecl *FD = FunctionDecl::Create(Context,
1904 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001905 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001906 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001907 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001908 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001909
1910 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1911
Adrian Prantl22e66b42014-04-11 01:13:04 +00001912 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001913
John McCall7f416cc2015-09-08 08:05:57 +00001914 if (generator.needsDispose()) {
1915 Address addr = CGF.GetAddrOfLocalVar(&src);
1916 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1917 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1918 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1919 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001920
John McCall7f416cc2015-09-08 08:05:57 +00001921 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001922 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001923
John McCallf9b056b2011-03-31 08:03:29 +00001924 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001925
John McCallf9b056b2011-03-31 08:03:29 +00001926 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001927}
1928
John McCallf9b056b2011-03-31 08:03:29 +00001929/// Build the dispose helper for a __block variable.
1930static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001931 const BlockByrefInfo &byrefInfo,
1932 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001933 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001934 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001935}
1936
John McCallf593b102013-01-22 03:56:22 +00001937/// Lazily build the copy and dispose helpers for a __block variable
1938/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001939template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001940static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1941 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001942 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001943 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001944
1945 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001946 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001947 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1948 if (node) return static_cast<T*>(node);
1949
John McCall7f416cc2015-09-08 08:05:57 +00001950 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1951 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001952
John McCall7f416cc2015-09-08 08:05:57 +00001953 T *copy = new (CGM.getContext()) T(std::move(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001954 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1955 return copy;
1956}
1957
John McCallf593b102013-01-22 03:56:22 +00001958/// Build the copy and dispose helpers for the given __block variable
1959/// emission. Places the helpers in the global cache. Returns null
1960/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001961BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001962CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001963 const AutoVarEmission &emission) {
1964 const VarDecl &var = *emission.Variable;
1965 QualType type = var.getType();
1966
John McCall7f416cc2015-09-08 08:05:57 +00001967 auto &byrefInfo = getBlockByrefInfo(&var);
1968
1969 // The alignment we care about for the purposes of uniquing byref
1970 // helpers is the alignment of the actual byref value field.
1971 CharUnits valueAlignment =
1972 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001973
John McCallf9b056b2011-03-31 08:03:29 +00001974 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1975 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001976 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001977
David Blaikie92551612015-08-13 23:53:09 +00001978 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001979 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001980 }
1981
John McCall31168b02011-06-15 23:02:42 +00001982 // Otherwise, if we don't have a retainable type, there's nothing to do.
1983 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001984 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001985
1986 Qualifiers qs = type.getQualifiers();
1987
1988 // If we have lifetime, that dominates.
1989 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001990 switch (lifetime) {
1991 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1992
1993 // These are just bits as far as the runtime is concerned.
1994 case Qualifiers::OCL_ExplicitNone:
1995 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001996 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001997
1998 // Tell the runtime that this is ARC __weak, called by the
1999 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002000 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002001 return ::buildByrefHelpers(CGM, byrefInfo,
2002 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002003
2004 // ARC __strong __block variables need to be retained.
2005 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002006 // Block pointers need to be copied, and there's no direct
2007 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002008 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002009 return ::buildByrefHelpers(CGM, byrefInfo,
2010 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002011
2012 // Otherwise, we transfer ownership of the retain from the stack
2013 // to the heap.
2014 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002015 return ::buildByrefHelpers(CGM, byrefInfo,
2016 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002017 }
2018 }
2019 llvm_unreachable("fell out of lifetime switch!");
2020 }
2021
John McCallf9b056b2011-03-31 08:03:29 +00002022 BlockFieldFlags flags;
2023 if (type->isBlockPointerType()) {
2024 flags |= BLOCK_FIELD_IS_BLOCK;
2025 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2026 type->isObjCObjectPointerType()) {
2027 flags |= BLOCK_FIELD_IS_OBJECT;
2028 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002029 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002030 }
2031
2032 if (type.isObjCGCWeak())
2033 flags |= BLOCK_FIELD_IS_WEAK;
2034
John McCall7f416cc2015-09-08 08:05:57 +00002035 return ::buildByrefHelpers(CGM, byrefInfo,
2036 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002037}
2038
John McCall7f416cc2015-09-08 08:05:57 +00002039Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2040 const VarDecl *var,
2041 bool followForward) {
2042 auto &info = getBlockByrefInfo(var);
2043 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002044}
2045
John McCall7f416cc2015-09-08 08:05:57 +00002046Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2047 const BlockByrefInfo &info,
2048 bool followForward,
2049 const llvm::Twine &name) {
2050 // Chase the forwarding address if requested.
2051 if (followForward) {
2052 Address forwardingAddr =
2053 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2054 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2055 }
2056
2057 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2058 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002059}
2060
John McCall7f416cc2015-09-08 08:05:57 +00002061/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002062/// into:
2063///
2064/// struct {
2065/// void *__isa;
2066/// void *__forwarding;
2067/// int32_t __flags;
2068/// int32_t __size;
2069/// void *__copy_helper; // only if needed
2070/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002071/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002072/// char padding[X]; // only if needed
2073/// T x;
2074/// } x
2075///
John McCall7f416cc2015-09-08 08:05:57 +00002076const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2077 auto it = BlockByrefInfos.find(D);
2078 if (it != BlockByrefInfos.end())
2079 return it->second;
John McCall73064872011-03-31 01:59:53 +00002080
John McCall7f416cc2015-09-08 08:05:57 +00002081 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002082 llvm::StructType::create(getLLVMContext(),
2083 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002084
John McCall7f416cc2015-09-08 08:05:57 +00002085 QualType Ty = D->getType();
2086
2087 CharUnits size;
2088 SmallVector<llvm::Type *, 8> types;
2089
John McCall73064872011-03-31 01:59:53 +00002090 // void *__isa;
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 *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002095 types.push_back(llvm::PointerType::getUnqual(byrefType));
2096 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002097
2098 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002099 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002100 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002101
2102 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002103 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002104 size += CharUnits::fromQuantity(4);
2105
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002106 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002107 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2108 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002109 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002110 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002111 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002112
2113 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002114 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002115 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002116 }
John McCall7f416cc2015-09-08 08:05:57 +00002117
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002118 bool HasByrefExtendedLayout = false;
2119 Qualifiers::ObjCLifetime Lifetime;
2120 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002121 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002122 /// void *__byref_variable_layout;
2123 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002124 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002125 }
2126
2127 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002128 llvm::Type *varTy = ConvertTypeForMem(Ty);
2129
2130 bool packed = false;
2131 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002132 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002133
2134 // We may have to insert padding.
2135 if (varOffset != size) {
2136 llvm::Type *paddingTy =
2137 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2138
2139 types.push_back(paddingTy);
2140 size = varOffset;
2141
2142 // Conversely, we might have to prevent LLVM from inserting padding.
2143 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2144 > varAlign.getQuantity()) {
2145 packed = true;
2146 }
2147 types.push_back(varTy);
2148
2149 byrefType->setBody(types, packed);
2150
2151 BlockByrefInfo info;
2152 info.Type = byrefType;
2153 info.FieldIndex = types.size() - 1;
2154 info.FieldOffset = varOffset;
2155 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2156
2157 auto pair = BlockByrefInfos.insert({D, info});
2158 assert(pair.second && "info was inserted recursively?");
2159 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002160}
2161
2162/// Initialize the structural components of a __block variable, i.e.
2163/// everything but the actual object.
2164void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002165 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002166 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002167
John McCallf9b056b2011-03-31 08:03:29 +00002168 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002169 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002170 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2171
2172 unsigned nextHeaderIndex = 0;
2173 CharUnits nextHeaderOffset;
2174 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2175 const Twine &name) {
2176 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2177 nextHeaderOffset, name);
2178 Builder.CreateStore(value, fieldAddr);
2179
2180 nextHeaderIndex++;
2181 nextHeaderOffset += fieldSize;
2182 };
John McCallf9b056b2011-03-31 08:03:29 +00002183
2184 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002185 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002186
2187 const VarDecl &D = *emission.Variable;
2188 QualType type = D.getType();
2189
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002190 bool HasByrefExtendedLayout;
2191 Qualifiers::ObjCLifetime ByrefLifetime;
2192 bool ByRefHasLifetime =
2193 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002194
John McCallf9b056b2011-03-31 08:03:29 +00002195 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002196
2197 // Initialize the 'isa', which is just 0 or 1.
2198 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002199 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002200 isa = 1;
2201 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002202 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002203
2204 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002205 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002206
2207 // Blocks ABI:
2208 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002209 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002210 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002211 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2212 if (ByRefHasLifetime) {
2213 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2214 else switch (ByrefLifetime) {
2215 case Qualifiers::OCL_Strong:
2216 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2217 break;
2218 case Qualifiers::OCL_Weak:
2219 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2220 break;
2221 case Qualifiers::OCL_ExplicitNone:
2222 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2223 break;
2224 case Qualifiers::OCL_None:
2225 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2226 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2227 break;
2228 default:
2229 break;
2230 }
2231 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2232 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2233 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2234 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2235 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2236 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2237 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2238 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2239 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2240 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2241 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2242 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2243 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2244 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2245 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2246 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2247 }
2248 printf("\n");
2249 }
2250 }
John McCall7f416cc2015-09-08 08:05:57 +00002251 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2252 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002253
John McCallf9b056b2011-03-31 08:03:29 +00002254 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2255 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002256 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002257
John McCallf9b056b2011-03-31 08:03:29 +00002258 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002259 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2260 "byref.copyHelper");
2261 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2262 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002263 }
John McCall7f416cc2015-09-08 08:05:57 +00002264
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002265 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002266 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2267 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002268 }
John McCall73064872011-03-31 01:59:53 +00002269}
2270
John McCallad7c5c12011-02-08 08:22:06 +00002271void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002272 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002273 llvm::Value *args[] = {
2274 Builder.CreateBitCast(V, Int8PtrTy),
2275 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2276 };
2277 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002278}
John McCall73064872011-03-31 01:59:53 +00002279
2280namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002281 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002282 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002283 llvm::Value *Addr;
2284 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2285
Craig Topper4f12f102014-03-12 06:41:41 +00002286 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002287 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002288 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2289 }
2290 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002291} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002292
2293/// Enter a cleanup to destroy a __block variable. Note that this
2294/// cleanup should be a no-op if the variable hasn't left the stack
2295/// yet; if a cleanup is required for the variable itself, that needs
2296/// to be done externally.
2297void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2298 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002299 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002300 return;
2301
John McCall7f416cc2015-09-08 08:05:57 +00002302 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2303 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002304}
John McCall7959fee2011-09-09 20:41:01 +00002305
2306/// Adjust the declaration of something from the blocks API.
2307static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2308 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002309 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002310
2311 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2312 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2313 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2314 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2315
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002316 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2317 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2318 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002319
2320 const NamedDecl *ND = nullptr;
2321 for (const auto &Result : DC->lookup(&II))
2322 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2323 (ND = dyn_cast<VarDecl>(Result)))
2324 break;
2325
2326 // TODO: support static blocks runtime
2327 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2328 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2329 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2330 } else {
2331 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2332 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2333 }
2334 }
2335
2336 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2337 return;
2338
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002339 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002340 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2341}
2342
2343llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2344 if (BlockObjectDispose)
2345 return BlockObjectDispose;
2346
2347 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2348 llvm::FunctionType *fty
2349 = llvm::FunctionType::get(VoidTy, args, false);
2350 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2351 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2352 return BlockObjectDispose;
2353}
2354
2355llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2356 if (BlockObjectAssign)
2357 return BlockObjectAssign;
2358
2359 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2360 llvm::FunctionType *fty
2361 = llvm::FunctionType::get(VoidTy, args, false);
2362 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2363 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2364 return BlockObjectAssign;
2365}
2366
2367llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2368 if (NSConcreteGlobalBlock)
2369 return NSConcreteGlobalBlock;
2370
2371 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002372 Int8PtrTy->getPointerTo(),
2373 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002374 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2375 return NSConcreteGlobalBlock;
2376}
2377
2378llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2379 if (NSConcreteStackBlock)
2380 return NSConcreteStackBlock;
2381
2382 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002383 Int8PtrTy->getPointerTo(),
2384 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002385 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002386 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002387}