blob: 6cf7f71ba5fcfcc4ff552de1c903ec466018184a [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"
John McCallde0fe072017-08-15 21:42:52 +000019#include "ConstantEmitter.h"
John McCall5ad74072017-03-02 20:04:19 +000020#include "clang/CodeGen/ConstantInitBuilder.h"
Mike Stump692c6e32009-03-20 21:53:12 +000021#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000022#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000023#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000026#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000027#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000028
Anders Carlsson2437cbf2009-02-12 00:39:25 +000029using namespace clang;
30using namespace CodeGen;
31
John McCall08ef4662011-11-10 08:15:53 +000032CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
33 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000034 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000035 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000036 DominatingIP(nullptr) {
37
John McCall08ef4662011-11-10 08:15:53 +000038 // Skip asm prefix, if any. 'name' is usually taken directly from
39 // the mangled name of the enclosing function.
40 if (!name.empty() && name[0] == '\01')
41 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000042}
43
John McCallf9b056b2011-03-31 08:03:29 +000044// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000045BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000046
John McCall351762c2011-02-07 10:33:21 +000047/// Build the given block as a global block.
48static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
49 const CGBlockInfo &blockInfo,
50 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000051
John McCall351762c2011-02-07 10:33:21 +000052/// Build the helper function to copy a block.
53static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
54 const CGBlockInfo &blockInfo) {
55 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
56}
57
Alp Tokerf6a24ce2013-12-05 16:25:25 +000058/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000059static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
60 const CGBlockInfo &blockInfo) {
61 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
62}
63
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000064/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
65/// buildBlockDescriptor is accessed from 5th field of the Block_literal
66/// meta-data and contains stationary information about the block literal.
67/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000068/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000069/// struct Block_descriptor {
70/// unsigned long reserved;
71/// unsigned long size; // size of Block_literal metadata in bytes.
72/// void *copy_func_helper_decl; // optional copy helper.
73/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000074/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000075/// void *block_layout_info; // encoding of captured block variables.
76/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000077/// \endcode
John McCall351762c2011-02-07 10:33:21 +000078static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
79 const CGBlockInfo &blockInfo) {
80 ASTContext &C = CGM.getContext();
81
John McCall6c9f1fdb2016-11-19 08:17:24 +000082 llvm::IntegerType *ulong =
83 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
84 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000085 if (CGM.getLangOpts().OpenCL)
86 i8p =
87 llvm::Type::getInt8PtrTy(
88 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
89 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000090 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000091
John McCall23c9dc62016-11-28 22:18:27 +000092 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +000093 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000094
95 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000096 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000097
98 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000099 // FIXME: What is the right way to say this doesn't fit? We should give
100 // a user diagnostic in that case. Better fix would be to change the
101 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000102 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000103
John McCall351762c2011-02-07 10:33:21 +0000104 // Optional copy/dispose helpers.
105 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000106 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000107 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000108
109 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000110 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000111 }
112
John McCall351762c2011-02-07 10:33:21 +0000113 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
114 std::string typeAtEncoding =
115 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000116 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000117 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000118
John McCall351762c2011-02-07 10:33:21 +0000119 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000120 if (C.getLangOpts().ObjC1) {
121 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000122 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000123 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000124 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000125 }
John McCall351762c2011-02-07 10:33:21 +0000126 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000127 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000128
Joey Goulyddbda402016-08-10 15:57:02 +0000129 unsigned AddrSpace = 0;
130 if (C.getLangOpts().OpenCL)
131 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000132
John McCall351762c2011-02-07 10:33:21 +0000133 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000134 elements.finishAndCreateGlobal("__block_descriptor_tmp",
135 CGM.getPointerAlign(),
136 /*constant*/ true,
137 llvm::GlobalValue::InternalLinkage,
138 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000139
John McCall351762c2011-02-07 10:33:21 +0000140 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000141}
142
John McCall351762c2011-02-07 10:33:21 +0000143/*
144 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000145
John McCall351762c2011-02-07 10:33:21 +0000146 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
147 struct Block_literal {
148 /// Initialized to one of:
149 /// extern void *_NSConcreteStackBlock[];
150 /// extern void *_NSConcreteGlobalBlock[];
151 ///
152 /// In theory, we could start one off malloc'ed by setting
153 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
154 /// this isa:
155 /// extern void *_NSConcreteMallocBlock[];
156 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000157
John McCall351762c2011-02-07 10:33:21 +0000158 /// These are the flags (with corresponding bit number) that the
159 /// compiler is actually supposed to know about.
160 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
161 /// descriptor provides copy and dispose helper functions
162 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
163 /// object with a nontrivial destructor or copy constructor
164 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
165 /// as global memory
166 /// 29. BLOCK_USE_STRET - indicates that the block function
167 /// uses stret, which objc_msgSend needs to know about
168 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
169 /// @encoded signature string
170 /// And we're not supposed to manipulate these:
171 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
172 /// to malloc'ed memory
173 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
174 /// to GC-allocated memory
175 /// Additionally, the bottom 16 bits are a reference count which
176 /// should be zero on the stack.
177 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000178
John McCall351762c2011-02-07 10:33:21 +0000179 /// Reserved; should be zero-initialized.
180 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000181
John McCall351762c2011-02-07 10:33:21 +0000182 /// Function pointer generated from block literal.
183 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000184
John McCall351762c2011-02-07 10:33:21 +0000185 /// Block description metadata generated from block literal.
186 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000187
John McCall351762c2011-02-07 10:33:21 +0000188 /// Captured values follow.
189 _CapturesTypes captures...;
190 };
191 */
David Chisnall950a9512009-11-17 19:33:30 +0000192
John McCall351762c2011-02-07 10:33:21 +0000193namespace {
194 /// A chunk of data that we actually have to capture in the block.
195 struct BlockLayoutChunk {
196 CharUnits Alignment;
197 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000198 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000199 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000200 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000201 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000202
John McCall351762c2011-02-07 10:33:21 +0000203 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000204 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000205 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000206 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000207 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000208 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000209
John McCall351762c2011-02-07 10:33:21 +0000210 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000211 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
212 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000213 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000214 info.CXXThisOffset = offset;
215 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000216 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
217 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000218 }
John McCall87fe5d52010-05-20 01:18:31 +0000219 }
John McCall351762c2011-02-07 10:33:21 +0000220 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000221
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000222 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
223 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000224 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000225 if (left.Alignment != right.Alignment)
226 return left.Alignment > right.Alignment;
227
228 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000229 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000230 return 1;
231 if (chunk.Lifetime == Qualifiers::OCL_Strong)
232 return 0;
233 if (chunk.Lifetime == Qualifiers::OCL_Weak)
234 return 2;
235 return 3;
236 };
237
238 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000239 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000240} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000241
John McCallb0a3ecb2011-02-08 03:07:00 +0000242/// Determines if the given type is safe for constant capture in C++.
243static bool isSafeForCXXConstantCapture(QualType type) {
244 const RecordType *recordType =
245 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
246
247 // Only records can be unsafe.
248 if (!recordType) return true;
249
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000250 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000251
252 // Maintain semantics for classes with non-trivial dtors or copy ctors.
253 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000254 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000255
256 // Otherwise, we just have to make sure there aren't any mutable
257 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000258 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000259}
260
John McCall351762c2011-02-07 10:33:21 +0000261/// It is illegal to modify a const object after initialization.
262/// Therefore, if a const object has a constant initializer, we don't
263/// actually need to keep storage for it in the block; we'll just
264/// rematerialize it at the start of the block function. This is
265/// acceptable because we make no promises about address stability of
266/// captured variables.
267static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000268 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000269 const VarDecl *var) {
Simon Pilgrim2c518802017-03-30 14:13:19 +0000270 // Return if this is a function parameter. We shouldn't try to
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000271 // rematerialize default arguments of function parameters.
272 if (isa<ParmVarDecl>(var))
273 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000274
John McCall351762c2011-02-07 10:33:21 +0000275 QualType type = var->getType();
276
277 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000278 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000279
John McCallb0a3ecb2011-02-08 03:07:00 +0000280 // Furthermore, in C++ we have to worry about mutable fields:
281 // C++ [dcl.type.cv]p4:
282 // Except that any class member declared mutable can be
283 // modified, any attempt to modify a const object during its
284 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000285 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000286 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000287
288 // If the variable doesn't have any initializer (shouldn't this be
289 // invalid?), it's not clear what we should do. Maybe capture as
290 // zero?
291 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000292 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000293
John McCallde0fe072017-08-15 21:42:52 +0000294 return ConstantEmitter(CGM, CGF).tryEmitAbstractForInitializer(*var);
John McCall351762c2011-02-07 10:33:21 +0000295}
296
297/// Get the low bit of a nonzero character count. This is the
298/// alignment of the nth byte if the 0th byte is universally aligned.
299static CharUnits getLowBit(CharUnits v) {
300 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
301}
302
303static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000304 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000305 // The header is basically 'struct { void *; int; int; void *; void *; }'.
306 // Assert that that struct is packed.
307 assert(CGM.getIntSize() <= CGM.getPointerSize());
308 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
309 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000310
John McCall7f416cc2015-09-08 08:05:57 +0000311 info.BlockAlign = CGM.getPointerAlign();
312 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000313
314 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000315 elementTypes.push_back(CGM.VoidPtrTy);
316 elementTypes.push_back(CGM.IntTy);
317 elementTypes.push_back(CGM.IntTy);
318 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000319 elementTypes.push_back(CGM.getBlockDescriptorType());
John McCall351762c2011-02-07 10:33:21 +0000320}
321
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000322static QualType getCaptureFieldType(const CodeGenFunction &CGF,
323 const BlockDecl::Capture &CI) {
324 const VarDecl *VD = CI.getVariable();
325
326 // If the variable is captured by an enclosing block or lambda expression,
327 // use the type of the capture field.
328 if (CGF.BlockInfo && CI.isNested())
329 return CGF.BlockInfo->getCapture(VD).fieldType();
330 if (auto *FD = CGF.LambdaCaptureFields.lookup(VD))
331 return FD->getType();
332 return VD->getType();
333}
334
John McCall351762c2011-02-07 10:33:21 +0000335/// Compute the layout of the given block. Attempts to lay the block
336/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000337static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
338 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000339 ASTContext &C = CGM.getContext();
340 const BlockDecl *block = info.getBlockDecl();
341
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000342 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000343 initializeForBlockHeader(CGM, info, elementTypes);
344
345 if (!block->hasCaptures()) {
346 info.StructureType =
347 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
348 info.CanBeGlobal = true;
349 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000350 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000351 else if (C.getLangOpts().ObjC1 &&
352 CGM.getLangOpts().getGC() == LangOptions::NonGC)
353 info.HasCapturedVariableLayout = true;
354
John McCall351762c2011-02-07 10:33:21 +0000355 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000356 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000357 layout.reserve(block->capturesCXXThis() +
358 (block->capture_end() - block->capture_begin()));
359
360 CharUnits maxFieldAlign;
361
362 // First, 'this'.
363 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000364 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
365 "Can't capture 'this' outside a method");
366 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000367
John McCall7f416cc2015-09-08 08:05:57 +0000368 // Theoretically, this could be in a different address space, so
369 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000370 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000371 std::pair<CharUnits,CharUnits> tinfo
372 = CGM.getContext().getTypeInfoInChars(thisType);
373 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
374
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000375 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
376 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000377 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000378 }
379
380 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000381 for (const auto &CI : block->captures()) {
382 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000383
Aaron Ballman9371dd22014-03-14 18:34:04 +0000384 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000385 // We have to copy/dispose of the __block reference.
386 info.NeedsCopyDispose = true;
387
John McCall351762c2011-02-07 10:33:21 +0000388 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000389 CharUnits align = CGM.getPointerAlign();
390 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000391
John McCall7f416cc2015-09-08 08:05:57 +0000392 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
393 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000394 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000395 continue;
396 }
397
398 // Otherwise, build a layout chunk with the size and alignment of
399 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000400 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000401 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
402 continue;
403 }
404
John McCall31168b02011-06-15 23:02:42 +0000405 // If we have a lifetime qualifier, honor it for capture purposes.
406 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000407 Qualifiers::ObjCLifetime lifetime =
408 variable->getType().getObjCLifetime();
409 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000410 switch (lifetime) {
411 case Qualifiers::OCL_None: llvm_unreachable("impossible");
412 case Qualifiers::OCL_ExplicitNone:
413 case Qualifiers::OCL_Autoreleasing:
414 break;
John McCall351762c2011-02-07 10:33:21 +0000415
John McCall31168b02011-06-15 23:02:42 +0000416 case Qualifiers::OCL_Strong:
417 case Qualifiers::OCL_Weak:
418 info.NeedsCopyDispose = true;
419 }
420
421 // Block pointers require copy/dispose. So do Objective-C pointers.
422 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000423 // But honor the inert __unsafe_unretained qualifier, which doesn't
424 // actually make it into the type system.
425 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
426 lifetime = Qualifiers::OCL_ExplicitNone;
427 } else {
428 info.NeedsCopyDispose = true;
429 // used for mrr below.
430 lifetime = Qualifiers::OCL_Strong;
431 }
John McCall351762c2011-02-07 10:33:21 +0000432
433 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000434 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000435 info.NeedsCopyDispose = true;
436 info.HasCXXObject = true;
437
438 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000439 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000440 if (const CXXRecordDecl *record =
441 variable->getType()->getAsCXXRecordDecl()) {
442 if (!record->hasTrivialDestructor()) {
443 info.HasCXXObject = true;
444 info.NeedsCopyDispose = true;
445 }
446 }
447 }
448
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000449 QualType VT = getCaptureFieldType(*CGF, CI);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000450 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000451 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000452
John McCall351762c2011-02-07 10:33:21 +0000453 maxFieldAlign = std::max(maxFieldAlign, align);
454
Jay Foad7c57be32011-07-11 09:56:20 +0000455 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000456 CGM.getTypes().ConvertTypeForMem(VT);
457
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000458 layout.push_back(
459 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000460 }
461
462 // If that was everything, we're done here.
463 if (layout.empty()) {
464 info.StructureType =
465 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
466 info.CanBeGlobal = true;
467 return;
468 }
469
470 // Sort the layout by alignment. We have to use a stable sort here
471 // to get reproducible results. There should probably be an
472 // llvm::array_pod_stable_sort.
473 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000474
475 // Needed for blocks layout info.
476 info.BlockHeaderForcedGapOffset = info.BlockSize;
477 info.BlockHeaderForcedGapSize = CharUnits::Zero();
478
John McCall351762c2011-02-07 10:33:21 +0000479 CharUnits &blockSize = info.BlockSize;
480 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
481
482 // Assuming that the first byte in the header is maximally aligned,
483 // get the alignment of the first byte following the header.
484 CharUnits endAlign = getLowBit(blockSize);
485
486 // If the end of the header isn't satisfactorily aligned for the
487 // maximum thing, look for things that are okay with the header-end
488 // alignment, and keep appending them until we get something that's
489 // aligned right. This algorithm is only guaranteed optimal if
490 // that condition is satisfied at some point; otherwise we can get
491 // things like:
492 // header // next byte has alignment 4
493 // something_with_size_5; // next byte has alignment 1
494 // something_with_alignment_8;
495 // which has 7 bytes of padding, as opposed to the naive solution
496 // which might have less (?).
497 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000499 li = layout.begin() + 1, le = layout.end();
500
501 // Look for something that the header end is already
502 // satisfactorily aligned for.
503 for (; li != le && endAlign < li->Alignment; ++li)
504 ;
505
506 // If we found something that's naturally aligned for the end of
507 // the header, keep adding things...
508 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000509 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000510 for (; li != le; ++li) {
511 assert(endAlign >= li->Alignment);
512
John McCall7f416cc2015-09-08 08:05:57 +0000513 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000514 elementTypes.push_back(li->Type);
515 blockSize += li->Size;
516 endAlign = getLowBit(blockSize);
517
518 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000519 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000520 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000521 }
John McCall351762c2011-02-07 10:33:21 +0000522 }
John McCall351762c2011-02-07 10:33:21 +0000523 // Don't re-append everything we just appended.
524 layout.erase(first, li);
525 }
526 }
527
John McCallac0350a2012-04-26 21:14:42 +0000528 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000529
John McCall351762c2011-02-07 10:33:21 +0000530 // At this point, we just have to add padding if the end align still
531 // isn't aligned right.
532 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000533 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000534 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000535
John McCall7f416cc2015-09-08 08:05:57 +0000536 // If we haven't yet added any fields, remember that there was an
537 // initial gap; this need to go into the block layout bit map.
538 if (blockSize == info.BlockHeaderForcedGapOffset) {
539 info.BlockHeaderForcedGapSize = padding;
540 }
541
John McCalle3dc1702011-02-15 09:22:45 +0000542 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
543 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000544 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000545 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000546 }
547
John McCall1db0a2f2012-05-01 20:28:00 +0000548 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000549 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000550 // Slam everything else on now. This works because they have
551 // strictly decreasing alignment and we expect that size is always a
552 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000553 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000554 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000555 if (endAlign < li->Alignment) {
556 // size may not be multiple of alignment. This can only happen with
557 // an over-aligned variable. We will be adding a padding field to
558 // make the size be multiple of alignment.
559 CharUnits padding = li->Alignment - endAlign;
560 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
561 padding.getQuantity()));
562 blockSize += padding;
563 endAlign = getLowBit(blockSize);
564 }
John McCall351762c2011-02-07 10:33:21 +0000565 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000566 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000567 elementTypes.push_back(li->Type);
568 blockSize += li->Size;
569 endAlign = getLowBit(blockSize);
570 }
571
572 info.StructureType =
573 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
574}
575
John McCall08ef4662011-11-10 08:15:53 +0000576/// Enter the scope of a block. This should be run at the entrance to
577/// a full-expression so that the block's cleanups are pushed at the
578/// right place in the stack.
579static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000580 assert(CGF.HaveInsertPoint());
581
John McCall08ef4662011-11-10 08:15:53 +0000582 // Allocate the block info and place it at the head of the list.
583 CGBlockInfo &blockInfo =
584 *new CGBlockInfo(block, CGF.CurFn->getName());
585 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
586 CGF.FirstBlockInfo = &blockInfo;
587
588 // Compute information about the layout, etc., of this block,
589 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000590 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000591
592 // Nothing else to do if it can be global.
593 if (blockInfo.CanBeGlobal) return;
594
595 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000596 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
597 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000598
599 // If there are cleanups to emit, enter them (but inactive).
600 if (!blockInfo.NeedsCopyDispose) return;
601
602 // Walk through the captures (in order) and find the ones not
603 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000604 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000605 // Ignore __block captures; there's nothing special in the
606 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000607 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000608
609 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000610 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000611 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
612 if (capture.isConstant()) continue;
613
614 // Ignore objects that aren't destructed.
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000615 QualType VT = getCaptureFieldType(CGF, CI);
616 QualType::DestructionKind dtorKind = VT.isDestructedType();
John McCall08ef4662011-11-10 08:15:53 +0000617 if (dtorKind == QualType::DK_none) continue;
618
619 CodeGenFunction::Destroyer *destroyer;
620
621 // Block captures count as local values and have imprecise semantics.
622 // They also can't be arrays, so need to worry about that.
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000623 //
624 // For const-qualified captures, emit clang.arc.use to ensure the captured
625 // object doesn't get released while we are still depending on its validity
626 // within the block.
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000627 if (VT.isConstQualified() &&
628 VT.getObjCLifetime() == Qualifiers::OCL_Strong &&
629 CGF.CGM.getCodeGenOpts().OptimizationLevel != 0) {
630 assert(CGF.CGM.getLangOpts().ObjCAutoRefCount &&
631 "expected ObjC ARC to be enabled");
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000632 destroyer = CodeGenFunction::emitARCIntrinsicUse;
Saleem Abdulrasoold95f6252017-05-05 18:39:06 +0000633 } else if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000634 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000635 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000636 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000637 }
638
639 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000640 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
641 capture.getIndex(),
642 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000643
John McCallf4beacd2011-11-10 10:43:54 +0000644 // We can use that GEP as the dominating IP.
645 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000646 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000647
John McCall08ef4662011-11-10 08:15:53 +0000648 CleanupKind cleanupKind = InactiveNormalCleanup;
649 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
650 if (useArrayEHCleanup)
651 cleanupKind = InactiveNormalAndEHCleanup;
652
Akira Hatanakaf1b3fc72017-02-14 06:46:55 +0000653 CGF.pushDestroy(cleanupKind, addr, VT,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000654 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000655
656 // Remember where that cleanup was.
657 capture.setCleanup(CGF.EHStack.stable_begin());
658 }
659}
660
661/// Enter a full-expression with a non-trivial number of objects to
662/// clean up. This is in this file because, at the moment, the only
663/// kind of cleanup object is a BlockDecl*.
664void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
665 assert(E->getNumObjects() != 0);
666 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
667 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
668 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
669 enterBlockScope(*this, *i);
670 }
671}
672
673/// Find the layout for the given block in a linked list and remove it.
674static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
675 const BlockDecl *block) {
676 while (true) {
677 assert(head && *head);
678 CGBlockInfo *cur = *head;
679
680 // If this is the block we're looking for, splice it out of the list.
681 if (cur->getBlockDecl() == block) {
682 *head = cur->NextBlockInfo;
683 return cur;
684 }
685
686 head = &cur->NextBlockInfo;
687 }
688}
689
690/// Destroy a chain of block layouts.
691void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
692 assert(head && "destroying an empty chain");
693 do {
694 CGBlockInfo *cur = head;
695 head = cur->NextBlockInfo;
696 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000697 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000698}
699
John McCall351762c2011-02-07 10:33:21 +0000700/// Emit a block literal expression in the current function.
701llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000702 // If the block has no captures, we won't have a pre-computed
703 // layout for it.
704 if (!blockExpr->getBlockDecl()->hasCaptures()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000705 if (llvm::Constant *Block = CGM.getAddrOfGlobalBlockIfEmitted(blockExpr))
706 return Block;
John McCall08ef4662011-11-10 08:15:53 +0000707 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000708 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000709 blockInfo.BlockExpression = blockExpr;
710 return EmitBlockLiteral(blockInfo);
711 }
John McCall351762c2011-02-07 10:33:21 +0000712
John McCall08ef4662011-11-10 08:15:53 +0000713 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000714 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000715 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
716 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000717
John McCall08ef4662011-11-10 08:15:53 +0000718 blockInfo->BlockExpression = blockExpr;
719 return EmitBlockLiteral(*blockInfo);
720}
721
722llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
723 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000724 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000725 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000726 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000727 LocalDeclMap,
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000728 isLambdaConv,
729 blockInfo.CanBeGlobal);
John McCalle3dc1702011-02-15 09:22:45 +0000730 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000731
732 // If there is nothing to capture, we can emit this as a global block.
733 if (blockInfo.CanBeGlobal)
Akira Hatanakaba0367a2017-09-22 21:32:06 +0000734 return CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression);
John McCall351762c2011-02-07 10:33:21 +0000735
736 // Otherwise, we have to emit this as a local block.
737
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000738 llvm::Constant *isa =
739 (!CGM.getContext().getLangOpts().OpenCL)
740 ? CGM.getNSConcreteStackBlock()
Yaxun Liucbf647c2017-07-08 13:24:52 +0000741 : CGM.getNullPointer(VoidPtrPtrTy,
742 CGM.getContext().getPointerType(
743 QualType(CGM.getContext().VoidPtrTy)));
John McCalle3dc1702011-02-15 09:22:45 +0000744 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000745
746 // Build the block descriptor.
747 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
748
John McCall7f416cc2015-09-08 08:05:57 +0000749 Address blockAddr = blockInfo.LocalAddress;
750 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000751
752 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000753 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000754 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000755 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
756 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000757 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000758
John McCall7f416cc2015-09-08 08:05:57 +0000759 auto projectField =
760 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
761 return Builder.CreateStructGEP(blockAddr, index, offset, name);
762 };
763 auto storeField =
764 [&](llvm::Value *value, unsigned index, CharUnits offset,
765 const Twine &name) {
766 Builder.CreateStore(value, projectField(index, offset, name));
767 };
768
769 // Initialize the block header.
770 {
771 // We assume all the header fields are densely packed.
772 unsigned index = 0;
773 CharUnits offset;
774 auto addHeaderField =
775 [&](llvm::Value *value, CharUnits size, const Twine &name) {
776 storeField(value, index, offset, name);
777 offset += size;
778 index++;
779 };
780
781 addHeaderField(isa, getPointerSize(), "block.isa");
782 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
783 getIntSize(), "block.flags");
784 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
785 getIntSize(), "block.reserved");
786 addHeaderField(blockFn, getPointerSize(), "block.invoke");
787 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
788 }
John McCall351762c2011-02-07 10:33:21 +0000789
790 // Finally, capture all the values into the block.
791 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
792
793 // First, 'this'.
794 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000795 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
796 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000797 Builder.CreateStore(LoadCXXThis(), addr);
798 }
799
800 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000801 for (const auto &CI : blockDecl->captures()) {
802 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000803 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
804
805 // Ignore constant captures.
806 if (capture.isConstant()) continue;
807
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000808 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000809
810 // This will be a [[type]]*, except that a byref entry will just be
811 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000812 Address blockField =
813 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000814
815 // Compute the address of the thing we're going to move into the
816 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000817 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000818
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000819 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000820 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000821 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000822 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000823 } else if (CI.isByRef()) {
824 if (BlockInfo && CI.isNested()) {
825 // We need to use the capture from the enclosing block.
826 const CGBlockInfo::Capture &enclosingCapture =
827 BlockInfo->getCapture(variable);
828
829 // This is a [[type]]*, except that a byref entry wil just be an i8**.
830 src = Builder.CreateStructGEP(LoadBlockStruct(),
831 enclosingCapture.getIndex(),
832 enclosingCapture.getOffset(),
833 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000834 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000835 auto I = LocalDeclMap.find(variable);
836 assert(I != LocalDeclMap.end());
837 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000838 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000839 } else {
840 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
841 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
842 type.getNonReferenceType(), VK_LValue,
843 SourceLocation());
844 src = EmitDeclRefLValue(&declRef).getAddress();
845 };
John McCall351762c2011-02-07 10:33:21 +0000846
847 // For byrefs, we just write the pointer to the byref struct into
848 // the block field. There's no need to chase the forwarding
849 // pointer at this point, since we're building something that will
850 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000851 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000852 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000853 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000854 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000855 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000856 else
John McCall7f416cc2015-09-08 08:05:57 +0000857 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000858
John McCalle3dc1702011-02-15 09:22:45 +0000859 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000860 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000861
862 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000863 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000864 if (blockDecl->isConversionFromLambda()) {
865 // If we have a lambda conversion, emit the expression
866 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000867 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000868 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000869 AggValueSlot::IsDestructed,
870 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000871 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000872 EmitAggExpr(copyExpr, Slot);
873 } else {
874 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
875 }
John McCall351762c2011-02-07 10:33:21 +0000876
877 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000878 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000879 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000880
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000881 // If type is const-qualified, copy the value into the block field.
882 } else if (type.isConstQualified() &&
Akira Hatanaka855d70c2017-05-09 01:20:05 +0000883 type.getObjCLifetime() == Qualifiers::OCL_Strong &&
884 CGM.getCodeGenOpts().OptimizationLevel != 0) {
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +0000885 llvm::Value *value = Builder.CreateLoad(src, "captured");
886 Builder.CreateStore(value, blockField);
887
John McCall4d14a902013-04-08 23:27:49 +0000888 // If this is an ARC __strong block-pointer variable, don't do a
889 // block copy.
890 //
891 // TODO: this can be generalized into the normal initialization logic:
892 // we should never need to do a block-copy when initializing a local
893 // variable, because the local variable's lifetime should be strictly
894 // contained within the stack block's.
895 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
896 type->isBlockPointerType()) {
897 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000898 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000899 value = EmitARCRetainNonBlock(value);
900
901 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000902 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000903
904 // Otherwise, fake up a POD copy into the block field.
905 } else {
John McCall31168b02011-06-15 23:02:42 +0000906 // Fake up a new variable so that EmitScalarInit doesn't think
907 // we're referring to the variable in its own initializer.
Alexey Bataev56223232017-06-09 13:40:18 +0000908 ImplicitParamDecl BlockFieldPseudoVar(getContext(), type,
909 ImplicitParamDecl::Other);
John McCall31168b02011-06-15 23:02:42 +0000910
John McCall93be3f72011-02-07 18:37:40 +0000911 // We use one of these or the other depending on whether the
912 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000913 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
914 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
915 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000916
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000917 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000918 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000919 // FIXME: Pass a specific location for the expr init so that the store is
920 // attributed to a reasonable location - otherwise it may be attributed to
921 // locations of subexpressions in the initialization.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000922 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Alexey Bataev56223232017-06-09 13:40:18 +0000923 EmitExprAsInit(&l2r, &BlockFieldPseudoVar,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000924 MakeAddrLValue(blockField, type, BaseInfo),
David Blaikie66e41972015-01-14 07:38:27 +0000925 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000926 }
927
John McCall08ef4662011-11-10 08:15:53 +0000928 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000929 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000930 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
931 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000932 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000933 }
John McCall351762c2011-02-07 10:33:21 +0000934 }
935
936 // Cast to the converted block-pointer type, which happens (somewhat
937 // unfortunately) to be a pointer to function type.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +0000938 llvm::Value *result = Builder.CreatePointerCast(
939 blockAddr.getPointer(), ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000940
John McCall351762c2011-02-07 10:33:21 +0000941 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000942}
943
944
Chris Lattnera5f58b02011-07-09 17:41:47 +0000945llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000946 if (BlockDescriptorType)
947 return BlockDescriptorType;
948
Chris Lattnera5f58b02011-07-09 17:41:47 +0000949 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000950 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000951
Mike Stump650c9322009-02-13 15:16:56 +0000952 // struct __block_descriptor {
953 // unsigned long reserved;
954 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000955 //
956 // // later, the following will be added
957 //
958 // struct {
959 // void (*copyHelper)();
960 // void (*copyHelper)();
961 // } helpers; // !!! optional
962 //
963 // const char *signature; // the block signature
964 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000965 // };
Serge Guelton1d993272017-05-09 19:31:30 +0000966 BlockDescriptorType = llvm::StructType::create(
967 "struct.__block_descriptor", UnsignedLongTy, UnsignedLongTy);
Mike Stump650c9322009-02-13 15:16:56 +0000968
John McCall351762c2011-02-07 10:33:21 +0000969 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +0000970 unsigned AddrSpace = 0;
971 if (getLangOpts().OpenCL)
972 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
973 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +0000974 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000975}
976
Chris Lattnera5f58b02011-07-09 17:41:47 +0000977llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000978 if (GenericBlockLiteralType)
979 return GenericBlockLiteralType;
980
Chris Lattnera5f58b02011-07-09 17:41:47 +0000981 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000982
Mike Stump005c9a62009-02-13 15:25:34 +0000983 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000984 // void *__isa;
985 // int __flags;
986 // int __reserved;
987 // void (*__invoke)(void *);
988 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000989 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000990 GenericBlockLiteralType =
Serge Guelton1d993272017-05-09 19:31:30 +0000991 llvm::StructType::create("struct.__block_literal_generic", VoidPtrTy,
992 IntTy, IntTy, VoidPtrTy, BlockDescPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000993
Mike Stump005c9a62009-02-13 15:25:34 +0000994 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000995}
996
Nick Lewycky2d84e842013-10-02 02:29:49 +0000997RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000998 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000999 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001000 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +00001001
John McCallb92ab1a2016-10-26 23:46:34 +00001002 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001003
1004 // Get a pointer to the generic block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001005 // For OpenCL we generate generic AS void ptr to be able to reuse the same
1006 // block definition for blocks with captures generated as private AS local
1007 // variables and without captures generated as global AS program scope
1008 // variables.
1009 unsigned AddrSpace = 0;
1010 if (getLangOpts().OpenCL)
1011 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1012
Chris Lattner2192fe52011-07-18 04:24:23 +00001013 llvm::Type *BlockLiteralTy =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001014 llvm::PointerType::get(CGM.getGenericBlockLiteralType(), AddrSpace);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001015
1016 // Bitcast the callee to a block literal.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001017 BlockPtr =
1018 Builder.CreatePointerCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001019
1020 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +00001021 llvm::Value *FuncPtr =
John McCallb92ab1a2016-10-26 23:46:34 +00001022 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001023
Mike Stumpb7074c02009-02-13 15:32:32 +00001024
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001025 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001026 CallArgList Args;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001027
1028 QualType VoidPtrQualTy = getContext().VoidPtrTy;
1029 llvm::Type *GenericVoidPtrTy = VoidPtrTy;
1030 if (getLangOpts().OpenCL) {
1031 GenericVoidPtrTy = Builder.getInt8PtrTy(
1032 getContext().getTargetAddressSpace(LangAS::opencl_generic));
1033 VoidPtrQualTy =
1034 getContext().getPointerType(getContext().getAddrSpaceQualType(
1035 getContext().VoidTy, LangAS::opencl_generic));
1036 }
1037
1038 BlockPtr = Builder.CreatePointerCast(BlockPtr, GenericVoidPtrTy);
1039 Args.add(RValue::get(BlockPtr), VoidPtrQualTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001040
Anders Carlsson479e6fc2009-04-08 23:13:16 +00001041 QualType FnType = BPT->getPointeeType();
1042
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001043 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001044 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001045
Anders Carlsson5f50c652009-04-07 22:10:22 +00001046 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001047 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001048
John McCall85915252011-03-09 08:39:33 +00001049 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001050 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001051 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001052
Anders Carlsson5f50c652009-04-07 22:10:22 +00001053 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001054 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001055
Chris Lattner2192fe52011-07-18 04:24:23 +00001056 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +00001057 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001058
John McCallb92ab1a2016-10-26 23:46:34 +00001059 // Prepare the callee.
1060 CGCallee Callee(CGCalleeInfo(), Func);
1061
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001062 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001063 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001064}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001065
John McCall7f416cc2015-09-08 08:05:57 +00001066Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1067 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001068 assert(BlockInfo && "evaluating block ref without block information?");
1069 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001070
John McCall351762c2011-02-07 10:33:21 +00001071 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001072 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001073
John McCall7f416cc2015-09-08 08:05:57 +00001074 Address addr =
1075 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1076 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001077
John McCall351762c2011-02-07 10:33:21 +00001078 if (isByRef) {
1079 // addr should be a void** right now. Load, then cast the result
1080 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001081
John McCall7f416cc2015-09-08 08:05:57 +00001082 auto &byrefInfo = getBlockByrefInfo(variable);
1083 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001084
John McCall7f416cc2015-09-08 08:05:57 +00001085 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1086 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001087
John McCall7f416cc2015-09-08 08:05:57 +00001088 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1089 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001090 }
1091
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001092 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001093 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001094
John McCall351762c2011-02-07 10:33:21 +00001095 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001096}
1097
George Burgess IVe3763372016-12-22 02:50:20 +00001098void CodeGenModule::setAddrOfGlobalBlock(const BlockExpr *BE,
1099 llvm::Constant *Addr) {
1100 bool Ok = EmittedGlobalBlocks.insert(std::make_pair(BE, Addr)).second;
1101 (void)Ok;
1102 assert(Ok && "Trying to replace an already-existing global block!");
1103}
1104
Mike Stump2d5a2872009-02-14 22:16:35 +00001105llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001106CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1107 StringRef Name) {
George Burgess IVe3763372016-12-22 02:50:20 +00001108 if (llvm::Constant *Block = getAddrOfGlobalBlockIfEmitted(BE))
1109 return Block;
1110
George Burgess IV70d15b32016-11-03 02:21:43 +00001111 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1112 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001113
John McCall351762c2011-02-07 10:33:21 +00001114 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001115 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001116
John McCall351762c2011-02-07 10:33:21 +00001117 // Using that metadata, generate the actual block function.
John McCall351762c2011-02-07 10:33:21 +00001118 {
John McCall7f416cc2015-09-08 08:05:57 +00001119 CodeGenFunction::DeclMapTy LocalDeclMap;
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001120 CodeGenFunction(*this).GenerateBlockFunction(
1121 GlobalDecl(), blockInfo, LocalDeclMap,
1122 /*IsLambdaConversionToBlock*/ false, /*BuildGlobalBlock*/ true);
John McCall351762c2011-02-07 10:33:21 +00001123 }
Mike Stumpb7074c02009-02-13 15:32:32 +00001124
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001125 return getAddrOfGlobalBlockIfEmitted(BE);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001126}
1127
John McCall351762c2011-02-07 10:33:21 +00001128static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1129 const CGBlockInfo &blockInfo,
1130 llvm::Constant *blockFn) {
1131 assert(blockInfo.CanBeGlobal);
George Burgess IVe3763372016-12-22 02:50:20 +00001132 // Callers should detect this case on their own: calling this function
1133 // generally requires computing layout information, which is a waste of time
1134 // if we've already emitted this block.
1135 assert(!CGM.getAddrOfGlobalBlockIfEmitted(blockInfo.BlockExpression) &&
1136 "Refusing to re-emit a global block.");
John McCall351762c2011-02-07 10:33:21 +00001137
1138 // Generate the constants for the block literal initializer.
John McCall23c9dc62016-11-28 22:18:27 +00001139 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001140 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001141
1142 // isa
Yaxun Liucbf647c2017-07-08 13:24:52 +00001143 fields.add((!CGM.getContext().getLangOpts().OpenCL)
1144 ? CGM.getNSConcreteGlobalBlock()
1145 : CGM.getNullPointer(CGM.VoidPtrPtrTy,
1146 CGM.getContext().getPointerType(QualType(
1147 CGM.getContext().VoidPtrTy))));
John McCall351762c2011-02-07 10:33:21 +00001148
1149 // __flags
John McCall85915252011-03-09 08:39:33 +00001150 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1151 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1152
John McCall6c9f1fdb2016-11-19 08:17:24 +00001153 fields.addInt(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001154
1155 // Reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +00001156 fields.addInt(CGM.IntTy, 0);
John McCall351762c2011-02-07 10:33:21 +00001157
1158 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001159 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001160
1161 // Descriptor
John McCall6c9f1fdb2016-11-19 08:17:24 +00001162 fields.add(buildBlockDescriptor(CGM, blockInfo));
John McCall351762c2011-02-07 10:33:21 +00001163
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001164 unsigned AddrSpace = 0;
1165 if (CGM.getContext().getLangOpts().OpenCL)
1166 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
1167
1168 llvm::Constant *literal = fields.finishAndCreateGlobal(
1169 "__block_literal_global", blockInfo.BlockAlign,
1170 /*constant*/ true, llvm::GlobalVariable::InternalLinkage, AddrSpace);
John McCall351762c2011-02-07 10:33:21 +00001171
1172 // Return a constant of the appropriately-casted type.
George Burgess IVe3763372016-12-22 02:50:20 +00001173 llvm::Type *RequiredType =
John McCall351762c2011-02-07 10:33:21 +00001174 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
George Burgess IVe3763372016-12-22 02:50:20 +00001175 llvm::Constant *Result =
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001176 llvm::ConstantExpr::getPointerCast(literal, RequiredType);
George Burgess IVe3763372016-12-22 02:50:20 +00001177 CGM.setAddrOfGlobalBlock(blockInfo.BlockExpression, Result);
1178 return Result;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001179}
1180
John McCall7f416cc2015-09-08 08:05:57 +00001181void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1182 unsigned argNum,
1183 llvm::Value *arg) {
1184 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1185
1186 llvm::Value *localAddr = nullptr;
1187 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1188 // Allocate a stack slot to let the debug info survive the RA.
1189 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1190 Builder.CreateStore(arg, alloc);
1191 localAddr = Builder.CreateLoad(alloc);
1192 }
1193
1194 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001195 if (CGM.getCodeGenOpts().getDebugInfo() >=
1196 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001197 DI->setLocation(D->getLocation());
1198 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1199 localAddr, Builder);
1200 }
1201 }
1202
1203 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1204 ApplyDebugLocation Scope(*this, StartLoc);
1205
1206 // Instead of messing around with LocalDeclMap, just set the value
1207 // directly as BlockPointer.
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001208 BlockPointer = Builder.CreatePointerCast(
1209 arg,
1210 BlockInfo->StructureType->getPointerTo(
1211 getContext().getLangOpts().OpenCL
1212 ? getContext().getTargetAddressSpace(LangAS::opencl_generic)
1213 : 0),
1214 "block");
John McCall7f416cc2015-09-08 08:05:57 +00001215}
1216
1217Address CodeGenFunction::LoadBlockStruct() {
1218 assert(BlockInfo && "not in a block invocation function!");
1219 assert(BlockPointer && "no block pointer set!");
1220 return Address(BlockPointer, BlockInfo->BlockAlign);
1221}
1222
Mike Stump4446dcf2009-03-05 08:32:30 +00001223llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001224CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1225 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001226 const DeclMapTy &ldm,
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001227 bool IsLambdaConversionToBlock,
1228 bool BuildGlobalBlock) {
John McCall351762c2011-02-07 10:33:21 +00001229 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001230
Fariborz Jahanian63628032012-06-26 16:06:38 +00001231 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001232
1233 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001234
John McCall351762c2011-02-07 10:33:21 +00001235 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001236
Mike Stump5469f292009-03-13 23:34:28 +00001237 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001238 // to be local to this function as well, in case they're directly
1239 // referenced in a block.
1240 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001241 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001242 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001243 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001244 }
1245
John McCall351762c2011-02-07 10:33:21 +00001246 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001247
John McCall351762c2011-02-07 10:33:21 +00001248 // Build the argument list.
1249 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001250
John McCall351762c2011-02-07 10:33:21 +00001251 // The first argument is the block pointer. Just take it as a void*
1252 // and cast it later.
1253 QualType selfTy = getContext().VoidPtrTy;
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001254
1255 // For OpenCL passed block pointer can be private AS local variable or
1256 // global AS program scope variable (for the case with and without captures).
Hiroshi Inouec5e54dd2017-07-03 08:49:44 +00001257 // Generic AS is used therefore to be able to accommodate both private and
Anastasia Stulovaaf0a7bb2017-01-27 15:11:34 +00001258 // generic AS in one implementation.
1259 if (getLangOpts().OpenCL)
1260 selfTy = getContext().getPointerType(getContext().getAddrSpaceQualType(
1261 getContext().VoidTy, LangAS::opencl_generic));
1262
Mike Stump7fe9cc12009-10-21 03:49:08 +00001263 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001264
Alexey Bataev56223232017-06-09 13:40:18 +00001265 ImplicitParamDecl SelfDecl(getContext(), const_cast<BlockDecl *>(blockDecl),
1266 SourceLocation(), II, selfTy,
1267 ImplicitParamDecl::ObjCSelf);
1268 args.push_back(&SelfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001269
John McCall351762c2011-02-07 10:33:21 +00001270 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001271 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001272
John McCall351762c2011-02-07 10:33:21 +00001273 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001274 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001275 const CGFunctionInfo &fnInfo =
1276 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001277 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001278 blockInfo.UsesStret = true;
1279
John McCalla729c622012-02-17 03:33:10 +00001280 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001281
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001282 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001283 llvm::Function *fn = llvm::Function::Create(
1284 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001285 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001286
Akira Hatanakaba0367a2017-09-22 21:32:06 +00001287 if (BuildGlobalBlock)
1288 buildGlobalBlock(CGM, blockInfo,
1289 llvm::ConstantExpr::getBitCast(fn, VoidPtrTy));
1290
John McCall351762c2011-02-07 10:33:21 +00001291 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001292 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001293 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001294 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001295
John McCall147d0212011-02-22 22:38:33 +00001296 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001297
Adrian Prantl0f6df002013-03-29 19:20:35 +00001298 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1299 // won't delete the dbg.declare intrinsics for captured variables.
1300 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1301 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1302 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001303 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1304 getPointerAlign(),
1305 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001306 // Set the DebugLocation to empty, so the store is recognized as a
1307 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001308 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001309 Builder.CreateStore(BlockPointer, Alloca);
1310 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001311 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001312
John McCall87fe5d52010-05-20 01:18:31 +00001313 // If we have a C++ 'this' reference, go ahead and force it into
1314 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001315 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001316 Address addr =
1317 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1318 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001319 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001320 }
1321
John McCall351762c2011-02-07 10:33:21 +00001322 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001323 for (const auto &CI : blockDecl->captures()) {
1324 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001325 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1326 if (!capture.isConstant()) continue;
1327
John McCall7f416cc2015-09-08 08:05:57 +00001328 CharUnits align = getContext().getDeclAlign(variable);
1329 Address alloca =
1330 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001331
John McCall7f416cc2015-09-08 08:05:57 +00001332 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001333
John McCall7f416cc2015-09-08 08:05:57 +00001334 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001335 }
1336
John McCall113bee02012-03-10 09:33:50 +00001337 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001338 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1339 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1340 --entry_ptr;
1341
Eli Friedman2495ab02012-02-25 02:48:22 +00001342 if (IsLambdaConversionToBlock)
1343 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001344 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001345 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001346 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001347 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001348 }
Mike Stump017460a2009-10-01 22:29:41 +00001349
Mike Stump7d699112009-10-01 00:27:30 +00001350 // Remember where we were...
1351 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001352
Mike Stump7d699112009-10-01 00:27:30 +00001353 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001354 ++entry_ptr;
1355 Builder.SetInsertPoint(entry, entry_ptr);
1356
John McCall113bee02012-03-10 09:33:50 +00001357 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001358 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001359 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001360 for (const auto &CI : blockDecl->captures()) {
1361 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001362 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001363
Benjamin Kramer8c305922016-02-02 11:06:51 +00001364 if (CGM.getCodeGenOpts().getDebugInfo() >=
1365 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001366 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1367 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001368 auto addr = LocalDeclMap.find(variable)->second;
1369 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001370 Builder);
1371 continue;
1372 }
John McCall351762c2011-02-07 10:33:21 +00001373
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001374 DI->EmitDeclareOfBlockDeclRefVariable(
1375 variable, BlockPointerDbgLoc, Builder, blockInfo,
1376 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001377 }
Mike Stump2e722b92009-09-30 02:43:10 +00001378 }
Manman Renab08a9a2013-01-04 18:51:35 +00001379 // Recover location if it was changed in the above loop.
1380 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001381 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001382 }
John McCall351762c2011-02-07 10:33:21 +00001383
Mike Stump7d699112009-10-01 00:27:30 +00001384 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001385 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001386 Builder.ClearInsertionPoint();
1387 else
1388 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001389
John McCall351762c2011-02-07 10:33:21 +00001390 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001391
John McCall351762c2011-02-07 10:33:21 +00001392 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001393}
Mike Stump1db7d042009-02-28 09:07:16 +00001394
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001395namespace {
1396
1397/// Represents a type of copy/destroy operation that should be performed for an
1398/// entity that's captured by a block.
1399enum class BlockCaptureEntityKind {
1400 CXXRecord, // Copy or destroy
1401 ARCWeak,
1402 ARCStrong,
1403 BlockObject, // Assign or release
1404 None
1405};
1406
1407/// Represents a captured entity that requires extra operations in order for
1408/// this entity to be copied or destroyed correctly.
1409struct BlockCaptureManagedEntity {
1410 BlockCaptureEntityKind Kind;
1411 BlockFieldFlags Flags;
1412 const BlockDecl::Capture &CI;
1413 const CGBlockInfo::Capture &Capture;
1414
1415 BlockCaptureManagedEntity(BlockCaptureEntityKind Type, BlockFieldFlags Flags,
1416 const BlockDecl::Capture &CI,
1417 const CGBlockInfo::Capture &Capture)
1418 : Kind(Type), Flags(Flags), CI(CI), Capture(Capture) {}
1419};
1420
1421} // end anonymous namespace
1422
1423static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1424computeCopyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1425 const LangOptions &LangOpts) {
1426 if (CI.getCopyExpr()) {
1427 assert(!CI.isByRef());
1428 // don't bother computing flags
1429 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1430 }
1431 BlockFieldFlags Flags;
1432 if (CI.isByRef()) {
1433 Flags = BLOCK_FIELD_IS_BYREF;
1434 if (T.isObjCGCWeak())
1435 Flags |= BLOCK_FIELD_IS_WEAK;
1436 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1437 }
1438 if (!T->isObjCRetainableType())
1439 // For all other types, the memcpy is fine.
1440 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1441
1442 Flags = BLOCK_FIELD_IS_OBJECT;
1443 bool isBlockPointer = T->isBlockPointerType();
1444 if (isBlockPointer)
1445 Flags = BLOCK_FIELD_IS_BLOCK;
1446
1447 // Special rules for ARC captures:
1448 Qualifiers QS = T.getQualifiers();
1449
1450 // We need to register __weak direct captures with the runtime.
1451 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1452 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1453
1454 // We need to retain the copied value for __strong direct captures.
1455 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong) {
1456 // If it's a block pointer, we have to copy the block and
1457 // assign that to the destination pointer, so we might as
1458 // well use _Block_object_assign. Otherwise we can avoid that.
1459 return std::make_pair(!isBlockPointer ? BlockCaptureEntityKind::ARCStrong
1460 : BlockCaptureEntityKind::BlockObject,
1461 Flags);
1462 }
1463
1464 // Non-ARC captures of retainable pointers are strong and
1465 // therefore require a call to _Block_object_assign.
1466 if (!QS.getObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1467 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1468
1469 // Otherwise the memcpy is fine.
1470 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1471}
1472
1473/// Find the set of block captures that need to be explicitly copied or destroy.
1474static void findBlockCapturedManagedEntities(
1475 const CGBlockInfo &BlockInfo, const LangOptions &LangOpts,
1476 SmallVectorImpl<BlockCaptureManagedEntity> &ManagedCaptures,
1477 llvm::function_ref<std::pair<BlockCaptureEntityKind, BlockFieldFlags>(
1478 const BlockDecl::Capture &, QualType, const LangOptions &)>
1479 Predicate) {
1480 for (const auto &CI : BlockInfo.getBlockDecl()->captures()) {
1481 const VarDecl *Variable = CI.getVariable();
1482 const CGBlockInfo::Capture &Capture = BlockInfo.getCapture(Variable);
1483 if (Capture.isConstant())
1484 continue;
1485
1486 auto Info = Predicate(CI, Variable->getType(), LangOpts);
1487 if (Info.first != BlockCaptureEntityKind::None)
1488 ManagedCaptures.emplace_back(Info.first, Info.second, CI, Capture);
1489 }
1490}
1491
John McCallf593b102013-01-22 03:56:22 +00001492/// Generate the copy-helper function for a block closure object:
1493/// static void block_copy_helper(block_t *dst, block_t *src);
1494/// The runtime will have previously initialized 'dst' by doing a
1495/// bit-copy of 'src'.
1496///
1497/// Note that this copies an entire block closure object to the heap;
1498/// it should not be confused with a 'byref copy helper', which moves
1499/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001500llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001501CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001502 ASTContext &C = getContext();
1503
1504 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001505 ImplicitParamDecl DstDecl(getContext(), C.VoidPtrTy,
1506 ImplicitParamDecl::Other);
1507 args.push_back(&DstDecl);
1508 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1509 ImplicitParamDecl::Other);
1510 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001511
John McCallc56a8b32016-03-11 04:30:31 +00001512 const CGFunctionInfo &FI =
1513 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001514
John McCall351762c2011-02-07 10:33:21 +00001515 // FIXME: it would be nice if these were mergeable with things with
1516 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001517 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001518
1519 llvm::Function *Fn =
1520 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001521 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001522
1523 IdentifierInfo *II
1524 = &CGM.getContext().Idents.get("__copy_helper_block_");
1525
John McCall351762c2011-02-07 10:33:21 +00001526 FunctionDecl *FD = FunctionDecl::Create(C,
1527 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001528 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001529 SourceLocation(), II, C.VoidTy,
1530 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001531 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001532 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001533
1534 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1535
Adrian Prantl95b24e92015-02-03 20:00:54 +00001536 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001537 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001538 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001539 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001540 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001541
Alexey Bataev56223232017-06-09 13:40:18 +00001542 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001543 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001544 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001545
Alexey Bataev56223232017-06-09 13:40:18 +00001546 Address dst = GetAddrOfLocalVar(&DstDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001547 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001548 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001549
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001550 SmallVector<BlockCaptureManagedEntity, 4> CopiedCaptures;
1551 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), CopiedCaptures,
1552 computeCopyInfoForBlockCapture);
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001553
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001554 for (const auto &CopiedCapture : CopiedCaptures) {
1555 const BlockDecl::Capture &CI = CopiedCapture.CI;
1556 const CGBlockInfo::Capture &capture = CopiedCapture.Capture;
1557 BlockFieldFlags flags = CopiedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001558
1559 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001560 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1561 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001562
1563 // If there's an explicit copy expression, we do that.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001564 if (CI.getCopyExpr()) {
1565 assert(CopiedCapture.Kind == BlockCaptureEntityKind::CXXRecord);
1566 EmitSynthesizedCXXCopyCtor(dstField, srcField, CI.getCopyExpr());
1567 } else if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001568 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001569 } else {
1570 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001571 if (CopiedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCalle68b8f42012-10-17 02:28:37 +00001572 // At -O0, store null into the destination field (so that the
1573 // storeStrong doesn't over-release) and then call storeStrong.
1574 // This is a workaround to not having an initStrong call.
1575 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001576 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001577 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1578 Builder.CreateStore(null, dstField);
1579 EmitARCStoreStrongCall(dstField, srcValue, true);
1580
1581 // With optimization enabled, take advantage of the fact that
1582 // the blocks runtime guarantees a memcpy of the block data, and
1583 // just emit a retain of the src field.
1584 } else {
1585 EmitARCRetainNonBlock(srcValue);
1586
1587 // We don't need this anymore, so kill it. It's not quite
1588 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001589 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001590 }
1591 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001592 assert(CopiedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCalle68b8f42012-10-17 02:28:37 +00001593 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001594 llvm::Value *dstAddr =
1595 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001596 llvm::Value *args[] = {
1597 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1598 };
1599
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001600 const VarDecl *variable = CI.getVariable();
John McCall882987f2013-02-28 19:01:20 +00001601 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001602 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001603 const Expr *copyExpr =
1604 CGM.getContext().getBlockVarCopyInits(variable);
1605 if (copyExpr) {
1606 copyCanThrow = true; // FIXME: reuse the noexcept logic
1607 }
1608 }
1609
1610 if (copyCanThrow) {
1611 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1612 } else {
1613 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1614 }
John McCalle68b8f42012-10-17 02:28:37 +00001615 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001616 }
1617 }
1618
John McCallad7c5c12011-02-08 08:22:06 +00001619 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001620
John McCalle3dc1702011-02-15 09:22:45 +00001621 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001622}
1623
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001624static std::pair<BlockCaptureEntityKind, BlockFieldFlags>
1625computeDestroyInfoForBlockCapture(const BlockDecl::Capture &CI, QualType T,
1626 const LangOptions &LangOpts) {
1627 BlockFieldFlags Flags;
1628 if (CI.isByRef()) {
1629 Flags = BLOCK_FIELD_IS_BYREF;
1630 if (T.isObjCGCWeak())
1631 Flags |= BLOCK_FIELD_IS_WEAK;
1632 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1633 }
1634
1635 if (const CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1636 if (Record->hasTrivialDestructor())
1637 return std::make_pair(BlockCaptureEntityKind::None, BlockFieldFlags());
1638 return std::make_pair(BlockCaptureEntityKind::CXXRecord, BlockFieldFlags());
1639 }
1640
1641 // Other types don't need to be destroy explicitly.
1642 if (!T->isObjCRetainableType())
1643 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1644
1645 Flags = BLOCK_FIELD_IS_OBJECT;
1646 if (T->isBlockPointerType())
1647 Flags = BLOCK_FIELD_IS_BLOCK;
1648
1649 // Special rules for ARC captures.
1650 Qualifiers QS = T.getQualifiers();
1651
1652 // Use objc_storeStrong for __strong direct captures; the
1653 // dynamic tools really like it when we do this.
1654 if (QS.getObjCLifetime() == Qualifiers::OCL_Strong)
1655 return std::make_pair(BlockCaptureEntityKind::ARCStrong, Flags);
1656
1657 // Support __weak direct captures.
1658 if (QS.getObjCLifetime() == Qualifiers::OCL_Weak)
1659 return std::make_pair(BlockCaptureEntityKind::ARCWeak, Flags);
1660
1661 // Non-ARC captures are strong, and we need to use
1662 // _Block_object_dispose.
1663 if (!QS.hasObjCLifetime() && !LangOpts.ObjCAutoRefCount)
1664 return std::make_pair(BlockCaptureEntityKind::BlockObject, Flags);
1665
1666 // Otherwise, we have nothing to do.
1667 return std::make_pair(BlockCaptureEntityKind::None, Flags);
1668}
1669
John McCallf593b102013-01-22 03:56:22 +00001670/// Generate the destroy-helper function for a block closure object:
1671/// static void block_destroy_helper(block_t *theBlock);
1672///
1673/// Note that this destroys a heap-allocated block closure object;
1674/// it should not be confused with a 'byref destroy helper', which
1675/// destroys the heap-allocated contents of an individual __block
1676/// variable.
John McCall351762c2011-02-07 10:33:21 +00001677llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001678CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001679 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001680
John McCall351762c2011-02-07 10:33:21 +00001681 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001682 ImplicitParamDecl SrcDecl(getContext(), C.VoidPtrTy,
1683 ImplicitParamDecl::Other);
1684 args.push_back(&SrcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001685
John McCallc56a8b32016-03-11 04:30:31 +00001686 const CGFunctionInfo &FI =
1687 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001688
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001689 // FIXME: We'd like to put these into a mergable by content, with
1690 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001691 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001692
1693 llvm::Function *Fn =
1694 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001695 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001696
1697 IdentifierInfo *II
1698 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1699
John McCall351762c2011-02-07 10:33:21 +00001700 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001701 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001702 SourceLocation(), II, C.VoidTy,
1703 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001704 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001705
1706 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1707
Adrian Prantl49a78562013-07-24 20:34:39 +00001708 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001709 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001710 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001711 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001712
Chris Lattner2192fe52011-07-18 04:24:23 +00001713 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001714
Alexey Bataev56223232017-06-09 13:40:18 +00001715 Address src = GetAddrOfLocalVar(&SrcDecl);
John McCall7f416cc2015-09-08 08:05:57 +00001716 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001717 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001718
John McCallad7c5c12011-02-08 08:22:06 +00001719 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001720
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001721 SmallVector<BlockCaptureManagedEntity, 4> DestroyedCaptures;
1722 findBlockCapturedManagedEntities(blockInfo, getLangOpts(), DestroyedCaptures,
1723 computeDestroyInfoForBlockCapture);
John McCall351762c2011-02-07 10:33:21 +00001724
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001725 for (const auto &DestroyedCapture : DestroyedCaptures) {
1726 const BlockDecl::Capture &CI = DestroyedCapture.CI;
1727 const CGBlockInfo::Capture &capture = DestroyedCapture.Capture;
1728 BlockFieldFlags flags = DestroyedCapture.Flags;
John McCall351762c2011-02-07 10:33:21 +00001729
John McCall7f416cc2015-09-08 08:05:57 +00001730 Address srcField =
1731 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001732
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001733 // If the captured record has a destructor then call it.
1734 if (DestroyedCapture.Kind == BlockCaptureEntityKind::CXXRecord) {
1735 const auto *Dtor =
1736 CI.getVariable()->getType()->getAsCXXRecordDecl()->getDestructor();
1737 PushDestructorCleanup(Dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001738
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001739 // If this is a __weak capture, emit the release directly.
1740 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCWeak) {
John McCall31168b02011-06-15 23:02:42 +00001741 EmitARCDestroyWeak(srcField);
1742
John McCalle68b8f42012-10-17 02:28:37 +00001743 // Destroy strong objects with a call if requested.
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001744 } else if (DestroyedCapture.Kind == BlockCaptureEntityKind::ARCStrong) {
John McCallcdda29c2013-03-13 03:10:54 +00001745 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001746
John McCall351762c2011-02-07 10:33:21 +00001747 // Otherwise we call _Block_object_dispose. It wouldn't be too
1748 // hard to just emit this as a cleanup if we wanted to make sure
1749 // that things were done in reverse.
1750 } else {
Alex Lorenze08e5bc2017-03-06 16:23:04 +00001751 assert(DestroyedCapture.Kind == BlockCaptureEntityKind::BlockObject);
John McCall351762c2011-02-07 10:33:21 +00001752 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001753 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001754 BuildBlockRelease(value, flags);
1755 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001756 }
1757
John McCall351762c2011-02-07 10:33:21 +00001758 cleanups.ForceCleanup();
1759
John McCallad7c5c12011-02-08 08:22:06 +00001760 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001761
John McCalle3dc1702011-02-15 09:22:45 +00001762 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001763}
1764
John McCallf9b056b2011-03-31 08:03:29 +00001765namespace {
1766
1767/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001768class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001769 BlockFieldFlags Flags;
1770
1771public:
1772 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001773 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001774
John McCall7f416cc2015-09-08 08:05:57 +00001775 void emitCopy(CodeGenFunction &CGF, Address destField,
1776 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001777 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1778
1779 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1780 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1781
1782 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1783
1784 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1785 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001786
John McCall7f416cc2015-09-08 08:05:57 +00001787 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001788 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001789 }
1790
John McCall7f416cc2015-09-08 08:05:57 +00001791 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001792 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1793 llvm::Value *value = CGF.Builder.CreateLoad(field);
1794
1795 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1796 }
1797
Craig Topper4f12f102014-03-12 06:41:41 +00001798 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001799 id.AddInteger(Flags.getBitMask());
1800 }
1801};
1802
John McCall31168b02011-06-15 23:02:42 +00001803/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001804class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001805public:
John McCall7f416cc2015-09-08 08:05:57 +00001806 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001807
John McCall7f416cc2015-09-08 08:05:57 +00001808 void emitCopy(CodeGenFunction &CGF, Address destField,
1809 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001810 CGF.EmitARCMoveWeak(destField, srcField);
1811 }
1812
John McCall7f416cc2015-09-08 08:05:57 +00001813 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001814 CGF.EmitARCDestroyWeak(field);
1815 }
1816
Craig Topper4f12f102014-03-12 06:41:41 +00001817 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001818 // 0 is distinguishable from all pointers and byref flags
1819 id.AddInteger(0);
1820 }
1821};
1822
1823/// Emits the copy/dispose helpers for an ARC __block __strong variable
1824/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001825class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001826public:
John McCall7f416cc2015-09-08 08:05:57 +00001827 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001828
John McCall7f416cc2015-09-08 08:05:57 +00001829 void emitCopy(CodeGenFunction &CGF, Address destField,
1830 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001831 // Do a "move" by copying the value and then zeroing out the old
1832 // variable.
1833
John McCall7f416cc2015-09-08 08:05:57 +00001834 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001835
John McCall31168b02011-06-15 23:02:42 +00001836 llvm::Value *null =
1837 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001838
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001839 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001840 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001841 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1842 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1843 return;
1844 }
John McCall7f416cc2015-09-08 08:05:57 +00001845 CGF.Builder.CreateStore(value, destField);
1846 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001847 }
1848
John McCall7f416cc2015-09-08 08:05:57 +00001849 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001850 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001851 }
1852
Craig Topper4f12f102014-03-12 06:41:41 +00001853 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001854 // 1 is distinguishable from all pointers and byref flags
1855 id.AddInteger(1);
1856 }
1857};
1858
John McCall3a237aa2011-11-09 03:17:26 +00001859/// Emits the copy/dispose helpers for an ARC __block __strong
1860/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001861class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001862public:
John McCall7f416cc2015-09-08 08:05:57 +00001863 ARCStrongBlockByrefHelpers(CharUnits alignment)
1864 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001865
John McCall7f416cc2015-09-08 08:05:57 +00001866 void emitCopy(CodeGenFunction &CGF, Address destField,
1867 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001868 // Do the copy with objc_retainBlock; that's all that
1869 // _Block_object_assign would do anyway, and we'd have to pass the
1870 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001871 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001872 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001873 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001874 }
1875
John McCall7f416cc2015-09-08 08:05:57 +00001876 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001877 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001878 }
1879
Craig Topper4f12f102014-03-12 06:41:41 +00001880 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001881 // 2 is distinguishable from all pointers and byref flags
1882 id.AddInteger(2);
1883 }
1884};
1885
John McCallf9b056b2011-03-31 08:03:29 +00001886/// Emits the copy/dispose helpers for a __block variable with a
1887/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001888class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001889 QualType VarType;
1890 const Expr *CopyExpr;
1891
1892public:
1893 CXXByrefHelpers(CharUnits alignment, QualType type,
1894 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001895 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001896
Craig Topper8a13c412014-05-21 05:09:00 +00001897 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001898 void emitCopy(CodeGenFunction &CGF, Address destField,
1899 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001900 if (!CopyExpr) return;
1901 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1902 }
1903
John McCall7f416cc2015-09-08 08:05:57 +00001904 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001905 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1906 CGF.PushDestructorCleanup(VarType, field);
1907 CGF.PopCleanupBlocks(cleanupDepth);
1908 }
1909
Craig Topper4f12f102014-03-12 06:41:41 +00001910 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001911 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1912 }
1913};
1914} // end anonymous namespace
1915
1916static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001917generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1918 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001919 ASTContext &Context = CGF.getContext();
1920
1921 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001922
John McCalla738c252011-03-09 04:27:21 +00001923 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00001924 ImplicitParamDecl Dst(CGF.getContext(), Context.VoidPtrTy,
1925 ImplicitParamDecl::Other);
1926 args.push_back(&Dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001927
Alexey Bataev56223232017-06-09 13:40:18 +00001928 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
1929 ImplicitParamDecl::Other);
1930 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCallc56a8b32016-03-11 04:30:31 +00001932 const CGFunctionInfo &FI =
1933 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001934
John McCall7f416cc2015-09-08 08:05:57 +00001935 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001936
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001937 // FIXME: We'd like to put these into a mergable by content, with
1938 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001939 llvm::Function *Fn =
1940 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001941 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001942
1943 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001944 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001945
John McCallf9b056b2011-03-31 08:03:29 +00001946 FunctionDecl *FD = FunctionDecl::Create(Context,
1947 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001948 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001949 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001950 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001951 false, false);
John McCall31168b02011-06-15 23:02:42 +00001952
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001953 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1954
Adrian Prantl22e66b42014-04-11 01:13:04 +00001955 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001956
John McCall7f416cc2015-09-08 08:05:57 +00001957 if (generator.needsCopy()) {
1958 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001959
John McCallf9b056b2011-03-31 08:03:29 +00001960 // dst->x
Alexey Bataev56223232017-06-09 13:40:18 +00001961 Address destField = CGF.GetAddrOfLocalVar(&Dst);
John McCall7f416cc2015-09-08 08:05:57 +00001962 destField = Address(CGF.Builder.CreateLoad(destField),
1963 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001964 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001965 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1966 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001967
John McCallf9b056b2011-03-31 08:03:29 +00001968 // src->x
Alexey Bataev56223232017-06-09 13:40:18 +00001969 Address srcField = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00001970 srcField = Address(CGF.Builder.CreateLoad(srcField),
1971 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001972 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001973 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1974 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001975
John McCall7f416cc2015-09-08 08:05:57 +00001976 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001977 }
1978
1979 CGF.FinishFunction();
1980
1981 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001982}
1983
John McCallf9b056b2011-03-31 08:03:29 +00001984/// Build the copy helper for a __block variable.
1985static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001986 const BlockByrefInfo &byrefInfo,
1987 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001988 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001989 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001990}
1991
1992/// Generate code for a __block variable's dispose helper.
1993static llvm::Constant *
1994generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001995 const BlockByrefInfo &byrefInfo,
1996 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001997 ASTContext &Context = CGF.getContext();
1998 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001999
John McCalla738c252011-03-09 04:27:21 +00002000 FunctionArgList args;
Alexey Bataev56223232017-06-09 13:40:18 +00002001 ImplicitParamDecl Src(CGF.getContext(), Context.VoidPtrTy,
2002 ImplicitParamDecl::Other);
2003 args.push_back(&Src);
Mike Stump11289f42009-09-09 15:08:12 +00002004
John McCallc56a8b32016-03-11 04:30:31 +00002005 const CGFunctionInfo &FI =
2006 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002007
John McCall7f416cc2015-09-08 08:05:57 +00002008 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002009
Mike Stumpcbc2bca2009-06-05 23:26:36 +00002010 // FIXME: We'd like to put these into a mergable by content, with
2011 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002012 llvm::Function *Fn =
2013 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00002014 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00002015 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002016
2017 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00002018 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002019
John McCallf9b056b2011-03-31 08:03:29 +00002020 FunctionDecl *FD = FunctionDecl::Create(Context,
2021 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002022 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002023 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00002024 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002025 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002026
2027 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
2028
Adrian Prantl22e66b42014-04-11 01:13:04 +00002029 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00002030
John McCall7f416cc2015-09-08 08:05:57 +00002031 if (generator.needsDispose()) {
Alexey Bataev56223232017-06-09 13:40:18 +00002032 Address addr = CGF.GetAddrOfLocalVar(&Src);
John McCall7f416cc2015-09-08 08:05:57 +00002033 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
2034 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
2035 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
2036 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00002037
John McCall7f416cc2015-09-08 08:05:57 +00002038 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00002039 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002040
John McCallf9b056b2011-03-31 08:03:29 +00002041 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00002042
John McCallf9b056b2011-03-31 08:03:29 +00002043 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002044}
2045
John McCallf9b056b2011-03-31 08:03:29 +00002046/// Build the dispose helper for a __block variable.
2047static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00002048 const BlockByrefInfo &byrefInfo,
2049 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002050 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00002051 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002052}
2053
John McCallf593b102013-01-22 03:56:22 +00002054/// Lazily build the copy and dispose helpers for a __block variable
2055/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00002056template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00002057static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
2058 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00002059 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00002060 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00002061
2062 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00002063 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00002064 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
2065 if (node) return static_cast<T*>(node);
2066
John McCall7f416cc2015-09-08 08:05:57 +00002067 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
2068 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00002069
Malcolm Parsonsf92d44c2016-12-06 14:49:18 +00002070 T *copy = new (CGM.getContext()) T(std::forward<T>(generator));
John McCallf9b056b2011-03-31 08:03:29 +00002071 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
2072 return copy;
2073}
2074
John McCallf593b102013-01-22 03:56:22 +00002075/// Build the copy and dispose helpers for the given __block variable
2076/// emission. Places the helpers in the global cache. Returns null
2077/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00002078BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00002079CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00002080 const AutoVarEmission &emission) {
2081 const VarDecl &var = *emission.Variable;
2082 QualType type = var.getType();
2083
John McCall7f416cc2015-09-08 08:05:57 +00002084 auto &byrefInfo = getBlockByrefInfo(&var);
2085
2086 // The alignment we care about for the purposes of uniquing byref
2087 // helpers is the alignment of the actual byref value field.
2088 CharUnits valueAlignment =
2089 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00002090
John McCallf9b056b2011-03-31 08:03:29 +00002091 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
2092 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00002093 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002094
David Blaikie92551612015-08-13 23:53:09 +00002095 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00002096 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00002097 }
2098
John McCall31168b02011-06-15 23:02:42 +00002099 // Otherwise, if we don't have a retainable type, there's nothing to do.
2100 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00002101 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002102
2103 Qualifiers qs = type.getQualifiers();
2104
2105 // If we have lifetime, that dominates.
2106 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00002107 switch (lifetime) {
2108 case Qualifiers::OCL_None: llvm_unreachable("impossible");
2109
2110 // These are just bits as far as the runtime is concerned.
2111 case Qualifiers::OCL_ExplicitNone:
2112 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00002113 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002114
2115 // Tell the runtime that this is ARC __weak, called by the
2116 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00002117 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00002118 return ::buildByrefHelpers(CGM, byrefInfo,
2119 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002120
2121 // ARC __strong __block variables need to be retained.
2122 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002123 // Block pointers need to be copied, and there's no direct
2124 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002125 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002126 return ::buildByrefHelpers(CGM, byrefInfo,
2127 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002128
2129 // Otherwise, we transfer ownership of the retain from the stack
2130 // to the heap.
2131 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002132 return ::buildByrefHelpers(CGM, byrefInfo,
2133 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002134 }
2135 }
2136 llvm_unreachable("fell out of lifetime switch!");
2137 }
2138
John McCallf9b056b2011-03-31 08:03:29 +00002139 BlockFieldFlags flags;
2140 if (type->isBlockPointerType()) {
2141 flags |= BLOCK_FIELD_IS_BLOCK;
2142 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2143 type->isObjCObjectPointerType()) {
2144 flags |= BLOCK_FIELD_IS_OBJECT;
2145 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002146 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002147 }
2148
2149 if (type.isObjCGCWeak())
2150 flags |= BLOCK_FIELD_IS_WEAK;
2151
John McCall7f416cc2015-09-08 08:05:57 +00002152 return ::buildByrefHelpers(CGM, byrefInfo,
2153 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002154}
2155
John McCall7f416cc2015-09-08 08:05:57 +00002156Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2157 const VarDecl *var,
2158 bool followForward) {
2159 auto &info = getBlockByrefInfo(var);
2160 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002161}
2162
John McCall7f416cc2015-09-08 08:05:57 +00002163Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2164 const BlockByrefInfo &info,
2165 bool followForward,
2166 const llvm::Twine &name) {
2167 // Chase the forwarding address if requested.
2168 if (followForward) {
2169 Address forwardingAddr =
2170 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2171 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2172 }
2173
2174 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2175 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002176}
2177
John McCall7f416cc2015-09-08 08:05:57 +00002178/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002179/// into:
2180///
2181/// struct {
2182/// void *__isa;
2183/// void *__forwarding;
2184/// int32_t __flags;
2185/// int32_t __size;
2186/// void *__copy_helper; // only if needed
2187/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002188/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002189/// char padding[X]; // only if needed
2190/// T x;
2191/// } x
2192///
John McCall7f416cc2015-09-08 08:05:57 +00002193const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2194 auto it = BlockByrefInfos.find(D);
2195 if (it != BlockByrefInfos.end())
2196 return it->second;
John McCall73064872011-03-31 01:59:53 +00002197
John McCall7f416cc2015-09-08 08:05:57 +00002198 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002199 llvm::StructType::create(getLLVMContext(),
2200 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002201
John McCall7f416cc2015-09-08 08:05:57 +00002202 QualType Ty = D->getType();
2203
2204 CharUnits size;
2205 SmallVector<llvm::Type *, 8> types;
2206
John McCall73064872011-03-31 01:59:53 +00002207 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002208 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002209 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002210
2211 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002212 types.push_back(llvm::PointerType::getUnqual(byrefType));
2213 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002214
2215 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002216 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002217 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002218
2219 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002220 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002221 size += CharUnits::fromQuantity(4);
2222
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002223 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002224 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2225 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002226 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002227 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002228 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002229
2230 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002231 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002232 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002233 }
John McCall7f416cc2015-09-08 08:05:57 +00002234
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002235 bool HasByrefExtendedLayout = false;
2236 Qualifiers::ObjCLifetime Lifetime;
2237 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002238 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002239 /// void *__byref_variable_layout;
2240 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002241 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002242 }
2243
2244 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002245 llvm::Type *varTy = ConvertTypeForMem(Ty);
2246
2247 bool packed = false;
2248 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002249 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002250
2251 // We may have to insert padding.
2252 if (varOffset != size) {
2253 llvm::Type *paddingTy =
2254 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2255
2256 types.push_back(paddingTy);
2257 size = varOffset;
2258
2259 // Conversely, we might have to prevent LLVM from inserting padding.
2260 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2261 > varAlign.getQuantity()) {
2262 packed = true;
2263 }
2264 types.push_back(varTy);
2265
2266 byrefType->setBody(types, packed);
2267
2268 BlockByrefInfo info;
2269 info.Type = byrefType;
2270 info.FieldIndex = types.size() - 1;
2271 info.FieldOffset = varOffset;
2272 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2273
2274 auto pair = BlockByrefInfos.insert({D, info});
2275 assert(pair.second && "info was inserted recursively?");
2276 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002277}
2278
2279/// Initialize the structural components of a __block variable, i.e.
2280/// everything but the actual object.
2281void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002282 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002283 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002284
John McCallf9b056b2011-03-31 08:03:29 +00002285 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002286 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002287 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2288
2289 unsigned nextHeaderIndex = 0;
2290 CharUnits nextHeaderOffset;
2291 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2292 const Twine &name) {
2293 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2294 nextHeaderOffset, name);
2295 Builder.CreateStore(value, fieldAddr);
2296
2297 nextHeaderIndex++;
2298 nextHeaderOffset += fieldSize;
2299 };
John McCallf9b056b2011-03-31 08:03:29 +00002300
2301 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002302 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002303
2304 const VarDecl &D = *emission.Variable;
2305 QualType type = D.getType();
2306
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002307 bool HasByrefExtendedLayout;
2308 Qualifiers::ObjCLifetime ByrefLifetime;
2309 bool ByRefHasLifetime =
2310 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002311
John McCallf9b056b2011-03-31 08:03:29 +00002312 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002313
2314 // Initialize the 'isa', which is just 0 or 1.
2315 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002316 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002317 isa = 1;
2318 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002319 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002320
2321 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002322 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002323
2324 // Blocks ABI:
2325 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002326 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002327 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002328 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2329 if (ByRefHasLifetime) {
2330 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2331 else switch (ByrefLifetime) {
2332 case Qualifiers::OCL_Strong:
2333 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2334 break;
2335 case Qualifiers::OCL_Weak:
2336 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2337 break;
2338 case Qualifiers::OCL_ExplicitNone:
2339 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2340 break;
2341 case Qualifiers::OCL_None:
2342 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2343 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2344 break;
2345 default:
2346 break;
2347 }
2348 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2349 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2350 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2351 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2352 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2353 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2354 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2355 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2356 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2357 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2358 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2359 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2360 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2361 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2362 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2363 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2364 }
2365 printf("\n");
2366 }
2367 }
John McCall7f416cc2015-09-08 08:05:57 +00002368 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2369 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002370
John McCallf9b056b2011-03-31 08:03:29 +00002371 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2372 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002373 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002374
John McCallf9b056b2011-03-31 08:03:29 +00002375 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002376 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2377 "byref.copyHelper");
2378 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2379 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002380 }
John McCall7f416cc2015-09-08 08:05:57 +00002381
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002382 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002383 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2384 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002385 }
John McCall73064872011-03-31 01:59:53 +00002386}
2387
John McCallad7c5c12011-02-08 08:22:06 +00002388void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002389 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002390 llvm::Value *args[] = {
2391 Builder.CreateBitCast(V, Int8PtrTy),
2392 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2393 };
2394 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002395}
John McCall73064872011-03-31 01:59:53 +00002396
2397namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002398 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002399 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002400 llvm::Value *Addr;
2401 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2402
Craig Topper4f12f102014-03-12 06:41:41 +00002403 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002404 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002405 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2406 }
2407 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002408} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002409
2410/// Enter a cleanup to destroy a __block variable. Note that this
2411/// cleanup should be a no-op if the variable hasn't left the stack
2412/// yet; if a cleanup is required for the variable itself, that needs
2413/// to be done externally.
2414void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2415 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002416 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002417 return;
2418
John McCall7f416cc2015-09-08 08:05:57 +00002419 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2420 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002421}
John McCall7959fee2011-09-09 20:41:01 +00002422
2423/// Adjust the declaration of something from the blocks API.
2424static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2425 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002426 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002427
2428 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2429 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2430 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2431 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2432
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002433 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2434 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2435 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002436
2437 const NamedDecl *ND = nullptr;
2438 for (const auto &Result : DC->lookup(&II))
2439 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2440 (ND = dyn_cast<VarDecl>(Result)))
2441 break;
2442
2443 // TODO: support static blocks runtime
2444 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2445 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2446 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2447 } else {
2448 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2449 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2450 }
2451 }
2452
2453 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2454 return;
2455
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002456 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002457 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2458}
2459
2460llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2461 if (BlockObjectDispose)
2462 return BlockObjectDispose;
2463
2464 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2465 llvm::FunctionType *fty
2466 = llvm::FunctionType::get(VoidTy, args, false);
2467 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2468 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2469 return BlockObjectDispose;
2470}
2471
2472llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2473 if (BlockObjectAssign)
2474 return BlockObjectAssign;
2475
2476 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2477 llvm::FunctionType *fty
2478 = llvm::FunctionType::get(VoidTy, args, false);
2479 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2480 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2481 return BlockObjectAssign;
2482}
2483
2484llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2485 if (NSConcreteGlobalBlock)
2486 return NSConcreteGlobalBlock;
2487
2488 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002489 Int8PtrTy->getPointerTo(),
2490 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002491 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2492 return NSConcreteGlobalBlock;
2493}
2494
2495llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2496 if (NSConcreteStackBlock)
2497 return NSConcreteStackBlock;
2498
2499 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002500 Int8PtrTy->getPointerTo(),
2501 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002502 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002503 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002504}