blob: 3b494bb20abc805365dc20a7fdf441dccba38e0f [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 McCall6c9f1fdb2016-11-19 08:17:24 +000019#include "ConstantBuilder.h"
Mike Stump692c6e32009-03-20 21:53:12 +000020#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000021#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000025#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000026#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000027
Anders Carlsson2437cbf2009-02-12 00:39:25 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall08ef4662011-11-10 08:15:53 +000031CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
32 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000033 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000034 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000035 DominatingIP(nullptr) {
36
John McCall08ef4662011-11-10 08:15:53 +000037 // Skip asm prefix, if any. 'name' is usually taken directly from
38 // the mangled name of the enclosing function.
39 if (!name.empty() && name[0] == '\01')
40 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000041}
42
John McCallf9b056b2011-03-31 08:03:29 +000043// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000044BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000045
John McCall351762c2011-02-07 10:33:21 +000046/// Build the given block as a global block.
47static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
48 const CGBlockInfo &blockInfo,
49 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000050
John McCall351762c2011-02-07 10:33:21 +000051/// Build the helper function to copy a block.
52static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
53 const CGBlockInfo &blockInfo) {
54 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
55}
56
Alp Tokerf6a24ce2013-12-05 16:25:25 +000057/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000058static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
59 const CGBlockInfo &blockInfo) {
60 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
61}
62
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000063/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
64/// buildBlockDescriptor is accessed from 5th field of the Block_literal
65/// meta-data and contains stationary information about the block literal.
66/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000067/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000068/// struct Block_descriptor {
69/// unsigned long reserved;
70/// unsigned long size; // size of Block_literal metadata in bytes.
71/// void *copy_func_helper_decl; // optional copy helper.
72/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000073/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000074/// void *block_layout_info; // encoding of captured block variables.
75/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000076/// \endcode
John McCall351762c2011-02-07 10:33:21 +000077static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
78 const CGBlockInfo &blockInfo) {
79 ASTContext &C = CGM.getContext();
80
John McCall6c9f1fdb2016-11-19 08:17:24 +000081 llvm::IntegerType *ulong =
82 cast<llvm::IntegerType>(CGM.getTypes().ConvertType(C.UnsignedLongTy));
83 llvm::PointerType *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000084 if (CGM.getLangOpts().OpenCL)
85 i8p =
86 llvm::Type::getInt8PtrTy(
87 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
88 else
John McCall6c9f1fdb2016-11-19 08:17:24 +000089 i8p = CGM.VoidPtrTy;
John McCall351762c2011-02-07 10:33:21 +000090
John McCall6c9f1fdb2016-11-19 08:17:24 +000091 ConstantBuilder builder(CGM);
92 auto elements = builder.beginStruct();
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +000095 elements.addInt(ulong, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000096
97 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000098 // FIXME: What is the right way to say this doesn't fit? We should give
99 // a user diagnostic in that case. Better fix would be to change the
100 // API to size_t.
John McCall6c9f1fdb2016-11-19 08:17:24 +0000101 elements.addInt(ulong, blockInfo.BlockSize.getQuantity());
Mike Stump85284ba2009-02-13 16:19:19 +0000102
John McCall351762c2011-02-07 10:33:21 +0000103 // Optional copy/dispose helpers.
104 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000105 // copy_func_helper_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000106 elements.add(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000107
108 // destroy_func_decl
John McCall6c9f1fdb2016-11-19 08:17:24 +0000109 elements.add(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000110 }
111
John McCall351762c2011-02-07 10:33:21 +0000112 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
113 std::string typeAtEncoding =
114 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
John McCall6c9f1fdb2016-11-19 08:17:24 +0000115 elements.add(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000116 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000117
John McCall351762c2011-02-07 10:33:21 +0000118 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000119 if (C.getLangOpts().ObjC1) {
120 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
John McCall6c9f1fdb2016-11-19 08:17:24 +0000121 elements.add(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000122 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000123 elements.add(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000124 }
John McCall351762c2011-02-07 10:33:21 +0000125 else
John McCall6c9f1fdb2016-11-19 08:17:24 +0000126 elements.addNullPointer(i8p);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
Joey Goulyddbda402016-08-10 15:57:02 +0000128 unsigned AddrSpace = 0;
129 if (C.getLangOpts().OpenCL)
130 AddrSpace = C.getTargetAddressSpace(LangAS::opencl_constant);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000131
John McCall351762c2011-02-07 10:33:21 +0000132 llvm::GlobalVariable *global =
John McCall6c9f1fdb2016-11-19 08:17:24 +0000133 elements.finishAndCreateGlobal("__block_descriptor_tmp",
134 CGM.getPointerAlign(),
135 /*constant*/ true,
136 llvm::GlobalValue::InternalLinkage,
137 AddrSpace);
Mike Stump85284ba2009-02-13 16:19:19 +0000138
John McCall351762c2011-02-07 10:33:21 +0000139 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000140}
141
John McCall351762c2011-02-07 10:33:21 +0000142/*
143 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000144
John McCall351762c2011-02-07 10:33:21 +0000145 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
146 struct Block_literal {
147 /// Initialized to one of:
148 /// extern void *_NSConcreteStackBlock[];
149 /// extern void *_NSConcreteGlobalBlock[];
150 ///
151 /// In theory, we could start one off malloc'ed by setting
152 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
153 /// this isa:
154 /// extern void *_NSConcreteMallocBlock[];
155 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000156
John McCall351762c2011-02-07 10:33:21 +0000157 /// These are the flags (with corresponding bit number) that the
158 /// compiler is actually supposed to know about.
159 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
160 /// descriptor provides copy and dispose helper functions
161 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
162 /// object with a nontrivial destructor or copy constructor
163 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
164 /// as global memory
165 /// 29. BLOCK_USE_STRET - indicates that the block function
166 /// uses stret, which objc_msgSend needs to know about
167 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
168 /// @encoded signature string
169 /// And we're not supposed to manipulate these:
170 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
171 /// to malloc'ed memory
172 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
173 /// to GC-allocated memory
174 /// Additionally, the bottom 16 bits are a reference count which
175 /// should be zero on the stack.
176 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Reserved; should be zero-initialized.
179 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Function pointer generated from block literal.
182 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000183
John McCall351762c2011-02-07 10:33:21 +0000184 /// Block description metadata generated from block literal.
185 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000186
John McCall351762c2011-02-07 10:33:21 +0000187 /// Captured values follow.
188 _CapturesTypes captures...;
189 };
190 */
David Chisnall950a9512009-11-17 19:33:30 +0000191
John McCall351762c2011-02-07 10:33:21 +0000192/// The number of fields in a block header.
George Burgess IVb9bd6fa2016-11-08 03:30:49 +0000193const static unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000194
John McCall351762c2011-02-07 10:33:21 +0000195namespace {
196 /// A chunk of data that we actually have to capture in the block.
197 struct BlockLayoutChunk {
198 CharUnits Alignment;
199 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000200 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000201 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000202 llvm::Type *Type;
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000203 QualType FieldType;
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000206 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000207 const BlockDecl::Capture *capture,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000208 llvm::Type *type, QualType fieldType)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000209 : Alignment(align), Size(size), Lifetime(lifetime),
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000210 Capture(capture), Type(type), FieldType(fieldType) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000211
John McCall351762c2011-02-07 10:33:21 +0000212 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000213 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
214 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000215 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000216 info.CXXThisOffset = offset;
217 } else {
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000218 auto C = CGBlockInfo::Capture::makeIndex(index, offset, FieldType);
219 info.Captures.insert({Capture->getVariable(), C});
John McCall7f416cc2015-09-08 08:05:57 +0000220 }
John McCall87fe5d52010-05-20 01:18:31 +0000221 }
John McCall351762c2011-02-07 10:33:21 +0000222 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000223
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000224 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
225 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000226 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000227 if (left.Alignment != right.Alignment)
228 return left.Alignment > right.Alignment;
229
230 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000231 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000232 return 1;
233 if (chunk.Lifetime == Qualifiers::OCL_Strong)
234 return 0;
235 if (chunk.Lifetime == Qualifiers::OCL_Weak)
236 return 2;
237 return 3;
238 };
239
240 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000241 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000242} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000243
John McCallb0a3ecb2011-02-08 03:07:00 +0000244/// Determines if the given type is safe for constant capture in C++.
245static bool isSafeForCXXConstantCapture(QualType type) {
246 const RecordType *recordType =
247 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
248
249 // Only records can be unsafe.
250 if (!recordType) return true;
251
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000252 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000253
254 // Maintain semantics for classes with non-trivial dtors or copy ctors.
255 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000256 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000257
258 // Otherwise, we just have to make sure there aren't any mutable
259 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000260 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000261}
262
John McCall351762c2011-02-07 10:33:21 +0000263/// It is illegal to modify a const object after initialization.
264/// Therefore, if a const object has a constant initializer, we don't
265/// actually need to keep storage for it in the block; we'll just
266/// rematerialize it at the start of the block function. This is
267/// acceptable because we make no promises about address stability of
268/// captured variables.
269static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000270 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000271 const VarDecl *var) {
Akira Hatanaka1cfa2732016-05-02 22:29:40 +0000272 // Return if this is a function paramter. We shouldn't try to
273 // rematerialize default arguments of function parameters.
274 if (isa<ParmVarDecl>(var))
275 return nullptr;
Akira Hatanaka3ba65352016-05-02 21:52:57 +0000276
John McCall351762c2011-02-07 10:33:21 +0000277 QualType type = var->getType();
278
279 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000280 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000281
John McCallb0a3ecb2011-02-08 03:07:00 +0000282 // Furthermore, in C++ we have to worry about mutable fields:
283 // C++ [dcl.type.cv]p4:
284 // Except that any class member declared mutable can be
285 // modified, any attempt to modify a const object during its
286 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000287 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000288 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000289
290 // If the variable doesn't have any initializer (shouldn't this be
291 // invalid?), it's not clear what we should do. Maybe capture as
292 // zero?
293 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000294 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000295
Richard Smithdafff942012-01-14 04:30:29 +0000296 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000297}
298
299/// Get the low bit of a nonzero character count. This is the
300/// alignment of the nth byte if the 0th byte is universally aligned.
301static CharUnits getLowBit(CharUnits v) {
302 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
303}
304
305static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000306 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000307 // The header is basically 'struct { void *; int; int; void *; void *; }'.
308 // Assert that that struct is packed.
309 assert(CGM.getIntSize() <= CGM.getPointerSize());
310 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
311 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000312
John McCall7f416cc2015-09-08 08:05:57 +0000313 info.BlockAlign = CGM.getPointerAlign();
314 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000315
316 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000317 elementTypes.push_back(CGM.VoidPtrTy);
318 elementTypes.push_back(CGM.IntTy);
319 elementTypes.push_back(CGM.IntTy);
320 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000321 elementTypes.push_back(CGM.getBlockDescriptorType());
322
323 assert(elementTypes.size() == BlockHeaderSize);
324}
325
326/// Compute the layout of the given block. Attempts to lay the block
327/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000328static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
329 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000330 ASTContext &C = CGM.getContext();
331 const BlockDecl *block = info.getBlockDecl();
332
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000333 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000334 initializeForBlockHeader(CGM, info, elementTypes);
335
336 if (!block->hasCaptures()) {
337 info.StructureType =
338 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
339 info.CanBeGlobal = true;
340 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000341 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000342 else if (C.getLangOpts().ObjC1 &&
343 CGM.getLangOpts().getGC() == LangOptions::NonGC)
344 info.HasCapturedVariableLayout = true;
345
John McCall351762c2011-02-07 10:33:21 +0000346 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000347 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000348 layout.reserve(block->capturesCXXThis() +
349 (block->capture_end() - block->capture_begin()));
350
351 CharUnits maxFieldAlign;
352
353 // First, 'this'.
354 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000355 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
356 "Can't capture 'this' outside a method");
357 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000358
John McCall7f416cc2015-09-08 08:05:57 +0000359 // Theoretically, this could be in a different address space, so
360 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000361 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000362 std::pair<CharUnits,CharUnits> tinfo
363 = CGM.getContext().getTypeInfoInChars(thisType);
364 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
365
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000366 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
367 Qualifiers::OCL_None,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000368 nullptr, llvmType, thisType));
John McCall351762c2011-02-07 10:33:21 +0000369 }
370
371 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000372 for (const auto &CI : block->captures()) {
373 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000374
Aaron Ballman9371dd22014-03-14 18:34:04 +0000375 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000376 // We have to copy/dispose of the __block reference.
377 info.NeedsCopyDispose = true;
378
John McCall351762c2011-02-07 10:33:21 +0000379 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000380 CharUnits align = CGM.getPointerAlign();
381 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000382
John McCall7f416cc2015-09-08 08:05:57 +0000383 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
384 Qualifiers::OCL_None, &CI,
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000385 CGM.VoidPtrTy, variable->getType()));
John McCall351762c2011-02-07 10:33:21 +0000386 continue;
387 }
388
389 // Otherwise, build a layout chunk with the size and alignment of
390 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000391 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000392 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
393 continue;
394 }
395
John McCall31168b02011-06-15 23:02:42 +0000396 // If we have a lifetime qualifier, honor it for capture purposes.
397 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000398 Qualifiers::ObjCLifetime lifetime =
399 variable->getType().getObjCLifetime();
400 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000401 switch (lifetime) {
402 case Qualifiers::OCL_None: llvm_unreachable("impossible");
403 case Qualifiers::OCL_ExplicitNone:
404 case Qualifiers::OCL_Autoreleasing:
405 break;
John McCall351762c2011-02-07 10:33:21 +0000406
John McCall31168b02011-06-15 23:02:42 +0000407 case Qualifiers::OCL_Strong:
408 case Qualifiers::OCL_Weak:
409 info.NeedsCopyDispose = true;
410 }
411
412 // Block pointers require copy/dispose. So do Objective-C pointers.
413 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000414 // But honor the inert __unsafe_unretained qualifier, which doesn't
415 // actually make it into the type system.
416 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
417 lifetime = Qualifiers::OCL_ExplicitNone;
418 } else {
419 info.NeedsCopyDispose = true;
420 // used for mrr below.
421 lifetime = Qualifiers::OCL_Strong;
422 }
John McCall351762c2011-02-07 10:33:21 +0000423
424 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000425 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000426 info.NeedsCopyDispose = true;
427 info.HasCXXObject = true;
428
429 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000431 if (const CXXRecordDecl *record =
432 variable->getType()->getAsCXXRecordDecl()) {
433 if (!record->hasTrivialDestructor()) {
434 info.HasCXXObject = true;
435 info.NeedsCopyDispose = true;
436 }
437 }
438 }
439
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000440 QualType VT = variable->getType();
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000441
442 // If the variable is captured by an enclosing block or lambda expression,
443 // use the type of the capture field.
444 if (CGF->BlockInfo && CI.isNested())
445 VT = CGF->BlockInfo->getCapture(variable).fieldType();
446 else if (auto *FD = CGF->LambdaCaptureFields.lookup(variable))
447 VT = FD->getType();
448
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000449 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000450 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000451
John McCall351762c2011-02-07 10:33:21 +0000452 maxFieldAlign = std::max(maxFieldAlign, align);
453
Jay Foad7c57be32011-07-11 09:56:20 +0000454 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000455 CGM.getTypes().ConvertTypeForMem(VT);
456
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000457 layout.push_back(
458 BlockLayoutChunk(align, size, lifetime, &CI, llvmType, VT));
John McCall351762c2011-02-07 10:33:21 +0000459 }
460
461 // If that was everything, we're done here.
462 if (layout.empty()) {
463 info.StructureType =
464 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
465 info.CanBeGlobal = true;
466 return;
467 }
468
469 // Sort the layout by alignment. We have to use a stable sort here
470 // to get reproducible results. There should probably be an
471 // llvm::array_pod_stable_sort.
472 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000473
474 // Needed for blocks layout info.
475 info.BlockHeaderForcedGapOffset = info.BlockSize;
476 info.BlockHeaderForcedGapSize = CharUnits::Zero();
477
John McCall351762c2011-02-07 10:33:21 +0000478 CharUnits &blockSize = info.BlockSize;
479 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
480
481 // Assuming that the first byte in the header is maximally aligned,
482 // get the alignment of the first byte following the header.
483 CharUnits endAlign = getLowBit(blockSize);
484
485 // If the end of the header isn't satisfactorily aligned for the
486 // maximum thing, look for things that are okay with the header-end
487 // alignment, and keep appending them until we get something that's
488 // aligned right. This algorithm is only guaranteed optimal if
489 // that condition is satisfied at some point; otherwise we can get
490 // things like:
491 // header // next byte has alignment 4
492 // something_with_size_5; // next byte has alignment 1
493 // something_with_alignment_8;
494 // which has 7 bytes of padding, as opposed to the naive solution
495 // which might have less (?).
496 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000498 li = layout.begin() + 1, le = layout.end();
499
500 // Look for something that the header end is already
501 // satisfactorily aligned for.
502 for (; li != le && endAlign < li->Alignment; ++li)
503 ;
504
505 // If we found something that's naturally aligned for the end of
506 // the header, keep adding things...
507 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000509 for (; li != le; ++li) {
510 assert(endAlign >= li->Alignment);
511
John McCall7f416cc2015-09-08 08:05:57 +0000512 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000513 elementTypes.push_back(li->Type);
514 blockSize += li->Size;
515 endAlign = getLowBit(blockSize);
516
517 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000518 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000519 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000520 }
John McCall351762c2011-02-07 10:33:21 +0000521 }
John McCall351762c2011-02-07 10:33:21 +0000522 // Don't re-append everything we just appended.
523 layout.erase(first, li);
524 }
525 }
526
John McCallac0350a2012-04-26 21:14:42 +0000527 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000528
John McCall351762c2011-02-07 10:33:21 +0000529 // At this point, we just have to add padding if the end align still
530 // isn't aligned right.
531 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000532 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000533 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000534
John McCall7f416cc2015-09-08 08:05:57 +0000535 // If we haven't yet added any fields, remember that there was an
536 // initial gap; this need to go into the block layout bit map.
537 if (blockSize == info.BlockHeaderForcedGapOffset) {
538 info.BlockHeaderForcedGapSize = padding;
539 }
540
John McCalle3dc1702011-02-15 09:22:45 +0000541 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
542 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000543 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000544 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000545 }
546
John McCall1db0a2f2012-05-01 20:28:00 +0000547 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000548 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000549 // Slam everything else on now. This works because they have
550 // strictly decreasing alignment and we expect that size is always a
551 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000552 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000553 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000554 if (endAlign < li->Alignment) {
555 // size may not be multiple of alignment. This can only happen with
556 // an over-aligned variable. We will be adding a padding field to
557 // make the size be multiple of alignment.
558 CharUnits padding = li->Alignment - endAlign;
559 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
560 padding.getQuantity()));
561 blockSize += padding;
562 endAlign = getLowBit(blockSize);
563 }
John McCall351762c2011-02-07 10:33:21 +0000564 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000565 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000566 elementTypes.push_back(li->Type);
567 blockSize += li->Size;
568 endAlign = getLowBit(blockSize);
569 }
570
571 info.StructureType =
572 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
573}
574
John McCall08ef4662011-11-10 08:15:53 +0000575/// Enter the scope of a block. This should be run at the entrance to
576/// a full-expression so that the block's cleanups are pushed at the
577/// right place in the stack.
578static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000579 assert(CGF.HaveInsertPoint());
580
John McCall08ef4662011-11-10 08:15:53 +0000581 // Allocate the block info and place it at the head of the list.
582 CGBlockInfo &blockInfo =
583 *new CGBlockInfo(block, CGF.CurFn->getName());
584 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
585 CGF.FirstBlockInfo = &blockInfo;
586
587 // Compute information about the layout, etc., of this block,
588 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000589 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000590
591 // Nothing else to do if it can be global.
592 if (blockInfo.CanBeGlobal) return;
593
594 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000595 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
596 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000597
598 // If there are cleanups to emit, enter them (but inactive).
599 if (!blockInfo.NeedsCopyDispose) return;
600
601 // Walk through the captures (in order) and find the ones not
602 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000603 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000604 // Ignore __block captures; there's nothing special in the
605 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000606 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000607
608 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000609 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000610 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
611 if (capture.isConstant()) continue;
612
613 // Ignore objects that aren't destructed.
614 QualType::DestructionKind dtorKind =
615 variable->getType().isDestructedType();
616 if (dtorKind == QualType::DK_none) continue;
617
618 CodeGenFunction::Destroyer *destroyer;
619
620 // Block captures count as local values and have imprecise semantics.
621 // They also can't be arrays, so need to worry about that.
622 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000623 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000624 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000625 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000626 }
627
628 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000629 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
630 capture.getIndex(),
631 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000632
John McCallf4beacd2011-11-10 10:43:54 +0000633 // We can use that GEP as the dominating IP.
634 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000635 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000636
John McCall08ef4662011-11-10 08:15:53 +0000637 CleanupKind cleanupKind = InactiveNormalCleanup;
638 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
639 if (useArrayEHCleanup)
640 cleanupKind = InactiveNormalAndEHCleanup;
641
642 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000643 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000644
645 // Remember where that cleanup was.
646 capture.setCleanup(CGF.EHStack.stable_begin());
647 }
648}
649
650/// Enter a full-expression with a non-trivial number of objects to
651/// clean up. This is in this file because, at the moment, the only
652/// kind of cleanup object is a BlockDecl*.
653void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
654 assert(E->getNumObjects() != 0);
655 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
656 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
657 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
658 enterBlockScope(*this, *i);
659 }
660}
661
662/// Find the layout for the given block in a linked list and remove it.
663static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
664 const BlockDecl *block) {
665 while (true) {
666 assert(head && *head);
667 CGBlockInfo *cur = *head;
668
669 // If this is the block we're looking for, splice it out of the list.
670 if (cur->getBlockDecl() == block) {
671 *head = cur->NextBlockInfo;
672 return cur;
673 }
674
675 head = &cur->NextBlockInfo;
676 }
677}
678
679/// Destroy a chain of block layouts.
680void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
681 assert(head && "destroying an empty chain");
682 do {
683 CGBlockInfo *cur = head;
684 head = cur->NextBlockInfo;
685 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000686 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000687}
688
John McCall351762c2011-02-07 10:33:21 +0000689/// Emit a block literal expression in the current function.
690llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000691 // If the block has no captures, we won't have a pre-computed
692 // layout for it.
693 if (!blockExpr->getBlockDecl()->hasCaptures()) {
694 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000695 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000696 blockInfo.BlockExpression = blockExpr;
697 return EmitBlockLiteral(blockInfo);
698 }
John McCall351762c2011-02-07 10:33:21 +0000699
John McCall08ef4662011-11-10 08:15:53 +0000700 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000701 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000702 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
703 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000704
John McCall08ef4662011-11-10 08:15:53 +0000705 blockInfo->BlockExpression = blockExpr;
706 return EmitBlockLiteral(*blockInfo);
707}
708
709llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
710 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000711 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000712 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000713 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000714 LocalDeclMap,
715 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000716 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000717
718 // If there is nothing to capture, we can emit this as a global block.
719 if (blockInfo.CanBeGlobal)
720 return buildGlobalBlock(CGM, blockInfo, blockFn);
721
722 // Otherwise, we have to emit this as a local block.
723
724 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000725 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000726
727 // Build the block descriptor.
728 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
729
John McCall7f416cc2015-09-08 08:05:57 +0000730 Address blockAddr = blockInfo.LocalAddress;
731 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000732
733 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000734 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000735 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000736 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
737 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000738 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000739
John McCall7f416cc2015-09-08 08:05:57 +0000740 auto projectField =
741 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
742 return Builder.CreateStructGEP(blockAddr, index, offset, name);
743 };
744 auto storeField =
745 [&](llvm::Value *value, unsigned index, CharUnits offset,
746 const Twine &name) {
747 Builder.CreateStore(value, projectField(index, offset, name));
748 };
749
750 // Initialize the block header.
751 {
752 // We assume all the header fields are densely packed.
753 unsigned index = 0;
754 CharUnits offset;
755 auto addHeaderField =
756 [&](llvm::Value *value, CharUnits size, const Twine &name) {
757 storeField(value, index, offset, name);
758 offset += size;
759 index++;
760 };
761
762 addHeaderField(isa, getPointerSize(), "block.isa");
763 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
764 getIntSize(), "block.flags");
765 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
766 getIntSize(), "block.reserved");
767 addHeaderField(blockFn, getPointerSize(), "block.invoke");
768 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
769 }
John McCall351762c2011-02-07 10:33:21 +0000770
771 // Finally, capture all the values into the block.
772 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
773
774 // First, 'this'.
775 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000776 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
777 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000778 Builder.CreateStore(LoadCXXThis(), addr);
779 }
780
781 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000782 for (const auto &CI : blockDecl->captures()) {
783 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000784 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
785
786 // Ignore constant captures.
787 if (capture.isConstant()) continue;
788
Akira Hatanakad542ccf2016-09-16 00:02:06 +0000789 QualType type = capture.fieldType();
John McCall351762c2011-02-07 10:33:21 +0000790
791 // This will be a [[type]]*, except that a byref entry will just be
792 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000793 Address blockField =
794 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000795
796 // Compute the address of the thing we're going to move into the
797 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000798 Address src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000799
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000800 if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000801 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000802 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000803 src = Address::invalid();
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000804 } else if (CI.isByRef()) {
805 if (BlockInfo && CI.isNested()) {
806 // We need to use the capture from the enclosing block.
807 const CGBlockInfo::Capture &enclosingCapture =
808 BlockInfo->getCapture(variable);
809
810 // This is a [[type]]*, except that a byref entry wil just be an i8**.
811 src = Builder.CreateStructGEP(LoadBlockStruct(),
812 enclosingCapture.getIndex(),
813 enclosingCapture.getOffset(),
814 "block.capture.addr");
John McCall7f416cc2015-09-08 08:05:57 +0000815 } else {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000816 auto I = LocalDeclMap.find(variable);
817 assert(I != LocalDeclMap.end());
818 src = I->second;
John McCalla37c2fa2013-03-04 06:32:36 +0000819 }
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000820 } else {
821 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
822 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
823 type.getNonReferenceType(), VK_LValue,
824 SourceLocation());
825 src = EmitDeclRefLValue(&declRef).getAddress();
826 };
John McCall351762c2011-02-07 10:33:21 +0000827
828 // For byrefs, we just write the pointer to the byref struct into
829 // the block field. There's no need to chase the forwarding
830 // pointer at this point, since we're building something that will
831 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000832 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000833 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000834 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000835 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000836 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000837 else
John McCall7f416cc2015-09-08 08:05:57 +0000838 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000839
John McCalle3dc1702011-02-15 09:22:45 +0000840 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000841 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000842
843 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000844 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000845 if (blockDecl->isConversionFromLambda()) {
846 // If we have a lambda conversion, emit the expression
847 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000848 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000849 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000850 AggValueSlot::IsDestructed,
851 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000852 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000853 EmitAggExpr(copyExpr, Slot);
854 } else {
855 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
856 }
John McCall351762c2011-02-07 10:33:21 +0000857
858 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000859 } else if (type->isReferenceType()) {
Akira Hatanaka1cce6e12016-05-04 18:40:33 +0000860 Builder.CreateStore(src.getPointer(), blockField);
John McCall4d14a902013-04-08 23:27:49 +0000861
862 // If this is an ARC __strong block-pointer variable, don't do a
863 // block copy.
864 //
865 // TODO: this can be generalized into the normal initialization logic:
866 // we should never need to do a block-copy when initializing a local
867 // variable, because the local variable's lifetime should be strictly
868 // contained within the stack block's.
869 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
870 type->isBlockPointerType()) {
871 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000872 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000873 value = EmitARCRetainNonBlock(value);
874
875 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000876 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000877
878 // Otherwise, fake up a POD copy into the block field.
879 } else {
John McCall31168b02011-06-15 23:02:42 +0000880 // Fake up a new variable so that EmitScalarInit doesn't think
881 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000882 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
883 SourceLocation(), /*name*/ nullptr,
884 type);
John McCall31168b02011-06-15 23:02:42 +0000885
John McCall93be3f72011-02-07 18:37:40 +0000886 // We use one of these or the other depending on whether the
887 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000888 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
889 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
890 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000891
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000892 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000893 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000894 // FIXME: Pass a specific location for the expr init so that the store is
895 // attributed to a reasonable location - otherwise it may be attributed to
896 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000897 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000898 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000899 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000900 }
901
John McCall08ef4662011-11-10 08:15:53 +0000902 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000903 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000904 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
905 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000906 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000907 }
John McCall351762c2011-02-07 10:33:21 +0000908 }
909
910 // Cast to the converted block-pointer type, which happens (somewhat
911 // unfortunately) to be a pointer to function type.
912 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000913 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000914 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000915
John McCall351762c2011-02-07 10:33:21 +0000916 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000917}
918
919
Chris Lattnera5f58b02011-07-09 17:41:47 +0000920llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000921 if (BlockDescriptorType)
922 return BlockDescriptorType;
923
Chris Lattnera5f58b02011-07-09 17:41:47 +0000924 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000925 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000926
Mike Stump650c9322009-02-13 15:16:56 +0000927 // struct __block_descriptor {
928 // unsigned long reserved;
929 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000930 //
931 // // later, the following will be added
932 //
933 // struct {
934 // void (*copyHelper)();
935 // void (*copyHelper)();
936 // } helpers; // !!! optional
937 //
938 // const char *signature; // the block signature
939 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000940 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000941 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000942 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000943 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000944
John McCall351762c2011-02-07 10:33:21 +0000945 // Now form a pointer to that.
Joey Goulyddbda402016-08-10 15:57:02 +0000946 unsigned AddrSpace = 0;
947 if (getLangOpts().OpenCL)
948 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
949 BlockDescriptorType = llvm::PointerType::get(BlockDescriptorType, AddrSpace);
Mike Stump650c9322009-02-13 15:16:56 +0000950 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000951}
952
Chris Lattnera5f58b02011-07-09 17:41:47 +0000953llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000954 if (GenericBlockLiteralType)
955 return GenericBlockLiteralType;
956
Chris Lattnera5f58b02011-07-09 17:41:47 +0000957 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000958
Mike Stump005c9a62009-02-13 15:25:34 +0000959 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000960 // void *__isa;
961 // int __flags;
962 // int __reserved;
963 // void (*__invoke)(void *);
964 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000965 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000966 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000967 llvm::StructType::create("struct.__block_literal_generic",
968 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000969 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000970
Mike Stump005c9a62009-02-13 15:25:34 +0000971 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000972}
973
Nick Lewycky2d84e842013-10-02 02:29:49 +0000974RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000975 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000976 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000977 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000978
John McCallb92ab1a2016-10-26 23:46:34 +0000979 llvm::Value *BlockPtr = EmitScalarExpr(E->getCallee());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000980
981 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000982 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000983 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000984
985 // Bitcast the callee to a block literal.
John McCallb92ab1a2016-10-26 23:46:34 +0000986 BlockPtr = Builder.CreateBitCast(BlockPtr, BlockLiteralTy, "block.literal");
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000987
988 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000989 llvm::Value *FuncPtr =
John McCallb92ab1a2016-10-26 23:46:34 +0000990 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockPtr, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000991
John McCallb92ab1a2016-10-26 23:46:34 +0000992 BlockPtr = Builder.CreateBitCast(BlockPtr, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000993
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000994 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000995 CallArgList Args;
John McCallb92ab1a2016-10-26 23:46:34 +0000996 Args.add(RValue::get(BlockPtr), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000997
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000998 QualType FnType = BPT->getPointeeType();
999
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001000 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +00001001 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +00001002
Anders Carlsson5f50c652009-04-07 22:10:22 +00001003 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +00001004 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +00001005
John McCall85915252011-03-09 08:39:33 +00001006 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +00001007 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +00001008 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +00001009
Anders Carlsson5f50c652009-04-07 22:10:22 +00001010 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +00001011 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001012
Chris Lattner2192fe52011-07-18 04:24:23 +00001013 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +00001014 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001015
John McCallb92ab1a2016-10-26 23:46:34 +00001016 // Prepare the callee.
1017 CGCallee Callee(CGCalleeInfo(), Func);
1018
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001019 // And call the block.
John McCallb92ab1a2016-10-26 23:46:34 +00001020 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +00001021}
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001022
John McCall7f416cc2015-09-08 08:05:57 +00001023Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1024 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001025 assert(BlockInfo && "evaluating block ref without block information?");
1026 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001027
John McCall351762c2011-02-07 10:33:21 +00001028 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001029 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001030
John McCall7f416cc2015-09-08 08:05:57 +00001031 Address addr =
1032 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1033 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001034
John McCall351762c2011-02-07 10:33:21 +00001035 if (isByRef) {
1036 // addr should be a void** right now. Load, then cast the result
1037 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001038
John McCall7f416cc2015-09-08 08:05:57 +00001039 auto &byrefInfo = getBlockByrefInfo(variable);
1040 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001041
John McCall7f416cc2015-09-08 08:05:57 +00001042 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1043 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001044
John McCall7f416cc2015-09-08 08:05:57 +00001045 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1046 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001047 }
1048
Akira Hatanakad542ccf2016-09-16 00:02:06 +00001049 if (auto refType = capture.fieldType()->getAs<ReferenceType>())
John McCall7f416cc2015-09-08 08:05:57 +00001050 addr = EmitLoadOfReference(addr, refType);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001051
John McCall351762c2011-02-07 10:33:21 +00001052 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001053}
1054
Mike Stump2d5a2872009-02-14 22:16:35 +00001055llvm::Constant *
George Burgess IV70d15b32016-11-03 02:21:43 +00001056CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE,
1057 StringRef Name) {
1058 CGBlockInfo blockInfo(BE->getBlockDecl(), Name);
1059 blockInfo.BlockExpression = BE;
Mike Stumpb7074c02009-02-13 15:32:32 +00001060
John McCall351762c2011-02-07 10:33:21 +00001061 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001062 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001063
John McCall351762c2011-02-07 10:33:21 +00001064 // Using that metadata, generate the actual block function.
1065 llvm::Constant *blockFn;
1066 {
John McCall7f416cc2015-09-08 08:05:57 +00001067 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001068 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1069 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001070 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001071 false);
John McCall351762c2011-02-07 10:33:21 +00001072 }
John McCalle3dc1702011-02-15 09:22:45 +00001073 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001074
John McCallad7c5c12011-02-08 08:22:06 +00001075 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001076}
1077
John McCall351762c2011-02-07 10:33:21 +00001078static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1079 const CGBlockInfo &blockInfo,
1080 llvm::Constant *blockFn) {
1081 assert(blockInfo.CanBeGlobal);
1082
1083 // Generate the constants for the block literal initializer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00001084 ConstantBuilder builder(CGM);
1085 auto fields = builder.beginStruct();
John McCall351762c2011-02-07 10:33:21 +00001086
1087 // isa
John McCall6c9f1fdb2016-11-19 08:17:24 +00001088 fields.add(CGM.getNSConcreteGlobalBlock());
John McCall351762c2011-02-07 10:33:21 +00001089
1090 // __flags
John McCall85915252011-03-09 08:39:33 +00001091 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1092 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1093
John McCall6c9f1fdb2016-11-19 08:17:24 +00001094 fields.addInt(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001095
1096 // Reserved
John McCall6c9f1fdb2016-11-19 08:17:24 +00001097 fields.addInt(CGM.IntTy, 0);
John McCall351762c2011-02-07 10:33:21 +00001098
1099 // Function
John McCall6c9f1fdb2016-11-19 08:17:24 +00001100 fields.add(blockFn);
John McCall351762c2011-02-07 10:33:21 +00001101
1102 // Descriptor
John McCall6c9f1fdb2016-11-19 08:17:24 +00001103 fields.add(buildBlockDescriptor(CGM, blockInfo));
John McCall351762c2011-02-07 10:33:21 +00001104
John McCall6c9f1fdb2016-11-19 08:17:24 +00001105 llvm::Constant *literal =
1106 fields.finishAndCreateGlobal("__block_literal_global",
1107 blockInfo.BlockAlign,
1108 /*constant*/ true);
John McCall351762c2011-02-07 10:33:21 +00001109
1110 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001111 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001112 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1113 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001114}
1115
John McCall7f416cc2015-09-08 08:05:57 +00001116void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1117 unsigned argNum,
1118 llvm::Value *arg) {
1119 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1120
1121 llvm::Value *localAddr = nullptr;
1122 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1123 // Allocate a stack slot to let the debug info survive the RA.
1124 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1125 Builder.CreateStore(arg, alloc);
1126 localAddr = Builder.CreateLoad(alloc);
1127 }
1128
1129 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001130 if (CGM.getCodeGenOpts().getDebugInfo() >=
1131 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001132 DI->setLocation(D->getLocation());
1133 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1134 localAddr, Builder);
1135 }
1136 }
1137
1138 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1139 ApplyDebugLocation Scope(*this, StartLoc);
1140
1141 // Instead of messing around with LocalDeclMap, just set the value
1142 // directly as BlockPointer.
1143 BlockPointer = Builder.CreateBitCast(arg,
1144 BlockInfo->StructureType->getPointerTo(),
1145 "block");
1146}
1147
1148Address CodeGenFunction::LoadBlockStruct() {
1149 assert(BlockInfo && "not in a block invocation function!");
1150 assert(BlockPointer && "no block pointer set!");
1151 return Address(BlockPointer, BlockInfo->BlockAlign);
1152}
1153
Mike Stump4446dcf2009-03-05 08:32:30 +00001154llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001155CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1156 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001157 const DeclMapTy &ldm,
1158 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001159 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001160
Fariborz Jahanian63628032012-06-26 16:06:38 +00001161 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001162
1163 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001164
John McCall351762c2011-02-07 10:33:21 +00001165 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001166
Mike Stump5469f292009-03-13 23:34:28 +00001167 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001168 // to be local to this function as well, in case they're directly
1169 // referenced in a block.
1170 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001171 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001172 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001173 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001174 }
1175
John McCall351762c2011-02-07 10:33:21 +00001176 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001177
John McCall351762c2011-02-07 10:33:21 +00001178 // Build the argument list.
1179 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001180
John McCall351762c2011-02-07 10:33:21 +00001181 // The first argument is the block pointer. Just take it as a void*
1182 // and cast it later.
1183 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001184 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001185
Richard Smith053f6c62014-05-16 23:01:30 +00001186 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001187 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001188 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001189
John McCall351762c2011-02-07 10:33:21 +00001190 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001191 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001192
John McCall351762c2011-02-07 10:33:21 +00001193 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001194 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
John McCallc56a8b32016-03-11 04:30:31 +00001195 const CGFunctionInfo &fnInfo =
1196 CGM.getTypes().arrangeBlockFunctionDeclaration(fnType, args);
Tim Northovere77cc392014-03-29 13:28:05 +00001197 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001198 blockInfo.UsesStret = true;
1199
John McCalla729c622012-02-17 03:33:10 +00001200 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001201
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001202 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001203 llvm::Function *fn = llvm::Function::Create(
1204 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001205 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001206
John McCall351762c2011-02-07 10:33:21 +00001207 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001208 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001209 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001210 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001211
John McCall147d0212011-02-22 22:38:33 +00001212 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001213
Adrian Prantl0f6df002013-03-29 19:20:35 +00001214 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1215 // won't delete the dbg.declare intrinsics for captured variables.
1216 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1217 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1218 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001219 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1220 getPointerAlign(),
1221 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001222 // Set the DebugLocation to empty, so the store is recognized as a
1223 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001224 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001225 Builder.CreateStore(BlockPointer, Alloca);
1226 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001227 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001228
John McCall87fe5d52010-05-20 01:18:31 +00001229 // If we have a C++ 'this' reference, go ahead and force it into
1230 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001231 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001232 Address addr =
1233 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1234 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001235 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001236 }
1237
John McCall351762c2011-02-07 10:33:21 +00001238 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001239 for (const auto &CI : blockDecl->captures()) {
1240 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001241 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1242 if (!capture.isConstant()) continue;
1243
John McCall7f416cc2015-09-08 08:05:57 +00001244 CharUnits align = getContext().getDeclAlign(variable);
1245 Address alloca =
1246 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001247
John McCall7f416cc2015-09-08 08:05:57 +00001248 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001249
John McCall7f416cc2015-09-08 08:05:57 +00001250 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001251 }
1252
John McCall113bee02012-03-10 09:33:50 +00001253 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001254 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1255 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1256 --entry_ptr;
1257
Eli Friedman2495ab02012-02-25 02:48:22 +00001258 if (IsLambdaConversionToBlock)
1259 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001260 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001261 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001262 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001263 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001264 }
Mike Stump017460a2009-10-01 22:29:41 +00001265
Mike Stump7d699112009-10-01 00:27:30 +00001266 // Remember where we were...
1267 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001268
Mike Stump7d699112009-10-01 00:27:30 +00001269 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001270 ++entry_ptr;
1271 Builder.SetInsertPoint(entry, entry_ptr);
1272
John McCall113bee02012-03-10 09:33:50 +00001273 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001274 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001275 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001276 for (const auto &CI : blockDecl->captures()) {
1277 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001278 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001279
Benjamin Kramer8c305922016-02-02 11:06:51 +00001280 if (CGM.getCodeGenOpts().getDebugInfo() >=
1281 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001282 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1283 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001284 auto addr = LocalDeclMap.find(variable)->second;
1285 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001286 Builder);
1287 continue;
1288 }
John McCall351762c2011-02-07 10:33:21 +00001289
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001290 DI->EmitDeclareOfBlockDeclRefVariable(
1291 variable, BlockPointerDbgLoc, Builder, blockInfo,
1292 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001293 }
Mike Stump2e722b92009-09-30 02:43:10 +00001294 }
Manman Renab08a9a2013-01-04 18:51:35 +00001295 // Recover location if it was changed in the above loop.
1296 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001297 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001298 }
John McCall351762c2011-02-07 10:33:21 +00001299
Mike Stump7d699112009-10-01 00:27:30 +00001300 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001301 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001302 Builder.ClearInsertionPoint();
1303 else
1304 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001305
John McCall351762c2011-02-07 10:33:21 +00001306 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001307
John McCall351762c2011-02-07 10:33:21 +00001308 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001309}
Mike Stump1db7d042009-02-28 09:07:16 +00001310
John McCall351762c2011-02-07 10:33:21 +00001311/*
1312 notes.push_back(HelperInfo());
1313 HelperInfo &note = notes.back();
1314 note.index = capture.getIndex();
1315 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1316 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001317
John McCall351762c2011-02-07 10:33:21 +00001318 if (ci->isByRef()) {
1319 note.flag = BLOCK_FIELD_IS_BYREF;
1320 if (type.isObjCGCWeak())
1321 note.flag |= BLOCK_FIELD_IS_WEAK;
1322 } else if (type->isBlockPointerType()) {
1323 note.flag = BLOCK_FIELD_IS_BLOCK;
1324 } else {
1325 note.flag = BLOCK_FIELD_IS_OBJECT;
1326 }
1327 */
Mike Stump1db7d042009-02-28 09:07:16 +00001328
John McCallf593b102013-01-22 03:56:22 +00001329/// Generate the copy-helper function for a block closure object:
1330/// static void block_copy_helper(block_t *dst, block_t *src);
1331/// The runtime will have previously initialized 'dst' by doing a
1332/// bit-copy of 'src'.
1333///
1334/// Note that this copies an entire block closure object to the heap;
1335/// it should not be confused with a 'byref copy helper', which moves
1336/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001337llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001338CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001339 ASTContext &C = getContext();
1340
1341 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001342 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1343 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001344 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001345 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1346 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001347 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001348
John McCallc56a8b32016-03-11 04:30:31 +00001349 const CGFunctionInfo &FI =
1350 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001351
John McCall351762c2011-02-07 10:33:21 +00001352 // FIXME: it would be nice if these were mergeable with things with
1353 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001354 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001355
1356 llvm::Function *Fn =
1357 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001358 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001359
1360 IdentifierInfo *II
1361 = &CGM.getContext().Idents.get("__copy_helper_block_");
1362
John McCall351762c2011-02-07 10:33:21 +00001363 FunctionDecl *FD = FunctionDecl::Create(C,
1364 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001365 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001366 SourceLocation(), II, C.VoidTy,
1367 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001368 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001369 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001370
1371 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1372
Adrian Prantl95b24e92015-02-03 20:00:54 +00001373 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001374 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001375 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001376 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001377 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001378
John McCall7f416cc2015-09-08 08:05:57 +00001379 Address src = GetAddrOfLocalVar(&srcDecl);
1380 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001381 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001382
John McCall7f416cc2015-09-08 08:05:57 +00001383 Address dst = GetAddrOfLocalVar(&dstDecl);
1384 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001385 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001386
John McCall351762c2011-02-07 10:33:21 +00001387 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001388
Aaron Ballman9371dd22014-03-14 18:34:04 +00001389 for (const auto &CI : blockDecl->captures()) {
1390 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001391 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001392
John McCall351762c2011-02-07 10:33:21 +00001393 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1394 if (capture.isConstant()) continue;
1395
Aaron Ballman9371dd22014-03-14 18:34:04 +00001396 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001397 BlockFieldFlags flags;
1398
John McCalle68b8f42012-10-17 02:28:37 +00001399 bool useARCWeakCopy = false;
1400 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001401
1402 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001403 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001404 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001405
Aaron Ballman9371dd22014-03-14 18:34:04 +00001406 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001407 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001408 if (type.isObjCGCWeak())
1409 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001410
John McCall31168b02011-06-15 23:02:42 +00001411 } else if (type->isObjCRetainableType()) {
1412 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001413 bool isBlockPointer = type->isBlockPointerType();
1414 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001415 flags = BLOCK_FIELD_IS_BLOCK;
1416
1417 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001418 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001419
John McCall460ce582015-10-22 18:38:17 +00001420 // We need to register __weak direct captures with the runtime.
1421 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1422 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001423
John McCall460ce582015-10-22 18:38:17 +00001424 // We need to retain the copied value for __strong direct captures.
1425 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1426 // If it's a block pointer, we have to copy the block and
1427 // assign that to the destination pointer, so we might as
1428 // well use _Block_object_assign. Otherwise we can avoid that.
1429 if (!isBlockPointer)
1430 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001431
1432 // Non-ARC captures of retainable pointers are strong and
1433 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001434 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001435 // fall through
John McCall460ce582015-10-22 18:38:17 +00001436
1437 // Otherwise the memcpy is fine.
1438 } else {
1439 continue;
John McCall31168b02011-06-15 23:02:42 +00001440 }
John McCall460ce582015-10-22 18:38:17 +00001441
1442 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001443 } else {
1444 continue;
1445 }
John McCall351762c2011-02-07 10:33:21 +00001446
1447 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001448 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1449 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001450
1451 // If there's an explicit copy expression, we do that.
1452 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001453 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001454 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001455 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001456 } else {
1457 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001458 if (useARCStrongCopy) {
1459 // At -O0, store null into the destination field (so that the
1460 // storeStrong doesn't over-release) and then call storeStrong.
1461 // This is a workaround to not having an initStrong call.
1462 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001463 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001464 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1465 Builder.CreateStore(null, dstField);
1466 EmitARCStoreStrongCall(dstField, srcValue, true);
1467
1468 // With optimization enabled, take advantage of the fact that
1469 // the blocks runtime guarantees a memcpy of the block data, and
1470 // just emit a retain of the src field.
1471 } else {
1472 EmitARCRetainNonBlock(srcValue);
1473
1474 // We don't need this anymore, so kill it. It's not quite
1475 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001476 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001477 }
1478 } else {
1479 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001480 llvm::Value *dstAddr =
1481 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001482 llvm::Value *args[] = {
1483 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1484 };
1485
1486 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001487 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001488 const Expr *copyExpr =
1489 CGM.getContext().getBlockVarCopyInits(variable);
1490 if (copyExpr) {
1491 copyCanThrow = true; // FIXME: reuse the noexcept logic
1492 }
1493 }
1494
1495 if (copyCanThrow) {
1496 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1497 } else {
1498 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1499 }
John McCalle68b8f42012-10-17 02:28:37 +00001500 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001501 }
1502 }
1503
John McCallad7c5c12011-02-08 08:22:06 +00001504 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001505
John McCalle3dc1702011-02-15 09:22:45 +00001506 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001507}
1508
John McCallf593b102013-01-22 03:56:22 +00001509/// Generate the destroy-helper function for a block closure object:
1510/// static void block_destroy_helper(block_t *theBlock);
1511///
1512/// Note that this destroys a heap-allocated block closure object;
1513/// it should not be confused with a 'byref destroy helper', which
1514/// destroys the heap-allocated contents of an individual __block
1515/// variable.
John McCall351762c2011-02-07 10:33:21 +00001516llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001517CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001518 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001519
John McCall351762c2011-02-07 10:33:21 +00001520 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001521 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1522 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001523 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001524
John McCallc56a8b32016-03-11 04:30:31 +00001525 const CGFunctionInfo &FI =
1526 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Mike Stump0c743272009-03-06 01:33:24 +00001527
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001528 // FIXME: We'd like to put these into a mergable by content, with
1529 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001530 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001531
1532 llvm::Function *Fn =
1533 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001534 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001535
1536 IdentifierInfo *II
1537 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1538
John McCall351762c2011-02-07 10:33:21 +00001539 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001540 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001541 SourceLocation(), II, C.VoidTy,
1542 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001543 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001544
1545 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1546
Adrian Prantl49a78562013-07-24 20:34:39 +00001547 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001548 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001549 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001550 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001551
Chris Lattner2192fe52011-07-18 04:24:23 +00001552 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001553
John McCall7f416cc2015-09-08 08:05:57 +00001554 Address src = GetAddrOfLocalVar(&srcDecl);
1555 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001556 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001557
John McCall351762c2011-02-07 10:33:21 +00001558 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1559
John McCallad7c5c12011-02-08 08:22:06 +00001560 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001561
Aaron Ballman9371dd22014-03-14 18:34:04 +00001562 for (const auto &CI : blockDecl->captures()) {
1563 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001564 QualType type = variable->getType();
1565
1566 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1567 if (capture.isConstant()) continue;
1568
John McCallad7c5c12011-02-08 08:22:06 +00001569 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001570 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001571
John McCalle68b8f42012-10-17 02:28:37 +00001572 bool useARCWeakDestroy = false;
1573 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001574
Aaron Ballman9371dd22014-03-14 18:34:04 +00001575 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001576 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001577 if (type.isObjCGCWeak())
1578 flags |= BLOCK_FIELD_IS_WEAK;
1579 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1580 if (record->hasTrivialDestructor())
1581 continue;
1582 dtor = record->getDestructor();
1583 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001584 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001585 if (type->isBlockPointerType())
1586 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001587
John McCall31168b02011-06-15 23:02:42 +00001588 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001589 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001590
John McCall460ce582015-10-22 18:38:17 +00001591 // Use objc_storeStrong for __strong direct captures; the
1592 // dynamic tools really like it when we do this.
1593 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1594 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001595
John McCall460ce582015-10-22 18:38:17 +00001596 // Support __weak direct captures.
1597 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1598 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001599
John McCall460ce582015-10-22 18:38:17 +00001600 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1601 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1602 // fall through
1603
1604 // Otherwise, we have nothing to do.
1605 } else {
1606 continue;
John McCall31168b02011-06-15 23:02:42 +00001607 }
1608 } else {
1609 continue;
1610 }
John McCall351762c2011-02-07 10:33:21 +00001611
John McCall7f416cc2015-09-08 08:05:57 +00001612 Address srcField =
1613 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001614
1615 // If there's an explicit copy expression, we do that.
1616 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001617 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001618
John McCall31168b02011-06-15 23:02:42 +00001619 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001620 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001621 EmitARCDestroyWeak(srcField);
1622
John McCalle68b8f42012-10-17 02:28:37 +00001623 // Destroy strong objects with a call if requested.
1624 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001625 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001626
John McCall351762c2011-02-07 10:33:21 +00001627 // Otherwise we call _Block_object_dispose. It wouldn't be too
1628 // hard to just emit this as a cleanup if we wanted to make sure
1629 // that things were done in reverse.
1630 } else {
1631 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001632 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001633 BuildBlockRelease(value, flags);
1634 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001635 }
1636
John McCall351762c2011-02-07 10:33:21 +00001637 cleanups.ForceCleanup();
1638
John McCallad7c5c12011-02-08 08:22:06 +00001639 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001640
John McCalle3dc1702011-02-15 09:22:45 +00001641 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001642}
1643
John McCallf9b056b2011-03-31 08:03:29 +00001644namespace {
1645
1646/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001647class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001648 BlockFieldFlags Flags;
1649
1650public:
1651 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001652 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001653
John McCall7f416cc2015-09-08 08:05:57 +00001654 void emitCopy(CodeGenFunction &CGF, Address destField,
1655 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001656 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1657
1658 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1659 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1660
1661 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1662
1663 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1664 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001665
John McCall7f416cc2015-09-08 08:05:57 +00001666 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001667 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001668 }
1669
John McCall7f416cc2015-09-08 08:05:57 +00001670 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001671 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1672 llvm::Value *value = CGF.Builder.CreateLoad(field);
1673
1674 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1675 }
1676
Craig Topper4f12f102014-03-12 06:41:41 +00001677 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001678 id.AddInteger(Flags.getBitMask());
1679 }
1680};
1681
John McCall31168b02011-06-15 23:02:42 +00001682/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001683class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001684public:
John McCall7f416cc2015-09-08 08:05:57 +00001685 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001686
John McCall7f416cc2015-09-08 08:05:57 +00001687 void emitCopy(CodeGenFunction &CGF, Address destField,
1688 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001689 CGF.EmitARCMoveWeak(destField, srcField);
1690 }
1691
John McCall7f416cc2015-09-08 08:05:57 +00001692 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001693 CGF.EmitARCDestroyWeak(field);
1694 }
1695
Craig Topper4f12f102014-03-12 06:41:41 +00001696 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001697 // 0 is distinguishable from all pointers and byref flags
1698 id.AddInteger(0);
1699 }
1700};
1701
1702/// Emits the copy/dispose helpers for an ARC __block __strong variable
1703/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001704class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001705public:
John McCall7f416cc2015-09-08 08:05:57 +00001706 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001707
John McCall7f416cc2015-09-08 08:05:57 +00001708 void emitCopy(CodeGenFunction &CGF, Address destField,
1709 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001710 // Do a "move" by copying the value and then zeroing out the old
1711 // variable.
1712
John McCall7f416cc2015-09-08 08:05:57 +00001713 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001714
John McCall31168b02011-06-15 23:02:42 +00001715 llvm::Value *null =
1716 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001717
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001718 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001719 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001720 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1721 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1722 return;
1723 }
John McCall7f416cc2015-09-08 08:05:57 +00001724 CGF.Builder.CreateStore(value, destField);
1725 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001726 }
1727
John McCall7f416cc2015-09-08 08:05:57 +00001728 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001729 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001730 }
1731
Craig Topper4f12f102014-03-12 06:41:41 +00001732 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001733 // 1 is distinguishable from all pointers and byref flags
1734 id.AddInteger(1);
1735 }
1736};
1737
John McCall3a237aa2011-11-09 03:17:26 +00001738/// Emits the copy/dispose helpers for an ARC __block __strong
1739/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001740class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001741public:
John McCall7f416cc2015-09-08 08:05:57 +00001742 ARCStrongBlockByrefHelpers(CharUnits alignment)
1743 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001744
John McCall7f416cc2015-09-08 08:05:57 +00001745 void emitCopy(CodeGenFunction &CGF, Address destField,
1746 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001747 // Do the copy with objc_retainBlock; that's all that
1748 // _Block_object_assign would do anyway, and we'd have to pass the
1749 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001750 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001751 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001752 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001753 }
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001756 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001757 }
1758
Craig Topper4f12f102014-03-12 06:41:41 +00001759 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001760 // 2 is distinguishable from all pointers and byref flags
1761 id.AddInteger(2);
1762 }
1763};
1764
John McCallf9b056b2011-03-31 08:03:29 +00001765/// Emits the copy/dispose helpers for a __block variable with a
1766/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001767class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001768 QualType VarType;
1769 const Expr *CopyExpr;
1770
1771public:
1772 CXXByrefHelpers(CharUnits alignment, QualType type,
1773 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001774 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001775
Craig Topper8a13c412014-05-21 05:09:00 +00001776 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001777 void emitCopy(CodeGenFunction &CGF, Address destField,
1778 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001779 if (!CopyExpr) return;
1780 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1781 }
1782
John McCall7f416cc2015-09-08 08:05:57 +00001783 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001784 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1785 CGF.PushDestructorCleanup(VarType, field);
1786 CGF.PopCleanupBlocks(cleanupDepth);
1787 }
1788
Craig Topper4f12f102014-03-12 06:41:41 +00001789 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001790 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1791 }
1792};
1793} // end anonymous namespace
1794
1795static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001796generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1797 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001798 ASTContext &Context = CGF.getContext();
1799
1800 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001801
John McCalla738c252011-03-09 04:27:21 +00001802 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001803 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001804 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001805 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001806
Craig Topper8a13c412014-05-21 05:09:00 +00001807 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001808 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001809 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001810
John McCallc56a8b32016-03-11 04:30:31 +00001811 const CGFunctionInfo &FI =
1812 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001813
John McCall7f416cc2015-09-08 08:05:57 +00001814 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001815
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001816 // FIXME: We'd like to put these into a mergable by content, with
1817 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001818 llvm::Function *Fn =
1819 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001820 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001821
1822 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001823 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001824
John McCallf9b056b2011-03-31 08:03:29 +00001825 FunctionDecl *FD = FunctionDecl::Create(Context,
1826 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001827 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001828 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001829 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001830 false, false);
John McCall31168b02011-06-15 23:02:42 +00001831
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001832 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1833
Adrian Prantl22e66b42014-04-11 01:13:04 +00001834 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001835
John McCall7f416cc2015-09-08 08:05:57 +00001836 if (generator.needsCopy()) {
1837 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001838
John McCallf9b056b2011-03-31 08:03:29 +00001839 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001840 Address destField = CGF.GetAddrOfLocalVar(&dst);
1841 destField = Address(CGF.Builder.CreateLoad(destField),
1842 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001843 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001844 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1845 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001846
John McCallf9b056b2011-03-31 08:03:29 +00001847 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001848 Address srcField = CGF.GetAddrOfLocalVar(&src);
1849 srcField = Address(CGF.Builder.CreateLoad(srcField),
1850 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001851 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001852 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1853 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001854
John McCall7f416cc2015-09-08 08:05:57 +00001855 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001856 }
1857
1858 CGF.FinishFunction();
1859
1860 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001861}
1862
John McCallf9b056b2011-03-31 08:03:29 +00001863/// Build the copy helper for a __block variable.
1864static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001865 const BlockByrefInfo &byrefInfo,
1866 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001867 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001868 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001869}
1870
1871/// Generate code for a __block variable's dispose helper.
1872static llvm::Constant *
1873generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001874 const BlockByrefInfo &byrefInfo,
1875 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001876 ASTContext &Context = CGF.getContext();
1877 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001878
John McCalla738c252011-03-09 04:27:21 +00001879 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001880 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001881 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001882 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001883
John McCallc56a8b32016-03-11 04:30:31 +00001884 const CGFunctionInfo &FI =
1885 CGF.CGM.getTypes().arrangeBuiltinFunctionDeclaration(R, args);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001888
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001889 // FIXME: We'd like to put these into a mergable by content, with
1890 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001891 llvm::Function *Fn =
1892 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001893 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001894 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001895
1896 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001897 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001898
John McCallf9b056b2011-03-31 08:03:29 +00001899 FunctionDecl *FD = FunctionDecl::Create(Context,
1900 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001901 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001902 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001903 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001904 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001905
1906 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1907
Adrian Prantl22e66b42014-04-11 01:13:04 +00001908 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001909
John McCall7f416cc2015-09-08 08:05:57 +00001910 if (generator.needsDispose()) {
1911 Address addr = CGF.GetAddrOfLocalVar(&src);
1912 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1913 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1914 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1915 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001916
John McCall7f416cc2015-09-08 08:05:57 +00001917 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001918 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001919
John McCallf9b056b2011-03-31 08:03:29 +00001920 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001921
John McCallf9b056b2011-03-31 08:03:29 +00001922 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001923}
1924
John McCallf9b056b2011-03-31 08:03:29 +00001925/// Build the dispose helper for a __block variable.
1926static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001927 const BlockByrefInfo &byrefInfo,
1928 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001929 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001930 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001931}
1932
John McCallf593b102013-01-22 03:56:22 +00001933/// Lazily build the copy and dispose helpers for a __block variable
1934/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001935template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001936static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1937 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001938 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001939 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001940
1941 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001942 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001943 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1944 if (node) return static_cast<T*>(node);
1945
John McCall7f416cc2015-09-08 08:05:57 +00001946 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1947 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001948
John McCall7f416cc2015-09-08 08:05:57 +00001949 T *copy = new (CGM.getContext()) T(std::move(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001950 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1951 return copy;
1952}
1953
John McCallf593b102013-01-22 03:56:22 +00001954/// Build the copy and dispose helpers for the given __block variable
1955/// emission. Places the helpers in the global cache. Returns null
1956/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001957BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001958CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001959 const AutoVarEmission &emission) {
1960 const VarDecl &var = *emission.Variable;
1961 QualType type = var.getType();
1962
John McCall7f416cc2015-09-08 08:05:57 +00001963 auto &byrefInfo = getBlockByrefInfo(&var);
1964
1965 // The alignment we care about for the purposes of uniquing byref
1966 // helpers is the alignment of the actual byref value field.
1967 CharUnits valueAlignment =
1968 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001969
John McCallf9b056b2011-03-31 08:03:29 +00001970 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1971 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001972 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001973
David Blaikie92551612015-08-13 23:53:09 +00001974 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001975 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001976 }
1977
John McCall31168b02011-06-15 23:02:42 +00001978 // Otherwise, if we don't have a retainable type, there's nothing to do.
1979 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001980 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001981
1982 Qualifiers qs = type.getQualifiers();
1983
1984 // If we have lifetime, that dominates.
1985 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001986 switch (lifetime) {
1987 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1988
1989 // These are just bits as far as the runtime is concerned.
1990 case Qualifiers::OCL_ExplicitNone:
1991 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001992 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001993
1994 // Tell the runtime that this is ARC __weak, called by the
1995 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001996 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00001997 return ::buildByrefHelpers(CGM, byrefInfo,
1998 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001999
2000 // ARC __strong __block variables need to be retained.
2001 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00002002 // Block pointers need to be copied, and there's no direct
2003 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00002004 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002005 return ::buildByrefHelpers(CGM, byrefInfo,
2006 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002007
2008 // Otherwise, we transfer ownership of the retain from the stack
2009 // to the heap.
2010 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002011 return ::buildByrefHelpers(CGM, byrefInfo,
2012 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00002013 }
2014 }
2015 llvm_unreachable("fell out of lifetime switch!");
2016 }
2017
John McCallf9b056b2011-03-31 08:03:29 +00002018 BlockFieldFlags flags;
2019 if (type->isBlockPointerType()) {
2020 flags |= BLOCK_FIELD_IS_BLOCK;
2021 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2022 type->isObjCObjectPointerType()) {
2023 flags |= BLOCK_FIELD_IS_OBJECT;
2024 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002025 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002026 }
2027
2028 if (type.isObjCGCWeak())
2029 flags |= BLOCK_FIELD_IS_WEAK;
2030
John McCall7f416cc2015-09-08 08:05:57 +00002031 return ::buildByrefHelpers(CGM, byrefInfo,
2032 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002033}
2034
John McCall7f416cc2015-09-08 08:05:57 +00002035Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2036 const VarDecl *var,
2037 bool followForward) {
2038 auto &info = getBlockByrefInfo(var);
2039 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002040}
2041
John McCall7f416cc2015-09-08 08:05:57 +00002042Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2043 const BlockByrefInfo &info,
2044 bool followForward,
2045 const llvm::Twine &name) {
2046 // Chase the forwarding address if requested.
2047 if (followForward) {
2048 Address forwardingAddr =
2049 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2050 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2051 }
2052
2053 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2054 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002055}
2056
John McCall7f416cc2015-09-08 08:05:57 +00002057/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002058/// into:
2059///
2060/// struct {
2061/// void *__isa;
2062/// void *__forwarding;
2063/// int32_t __flags;
2064/// int32_t __size;
2065/// void *__copy_helper; // only if needed
2066/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002067/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002068/// char padding[X]; // only if needed
2069/// T x;
2070/// } x
2071///
John McCall7f416cc2015-09-08 08:05:57 +00002072const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2073 auto it = BlockByrefInfos.find(D);
2074 if (it != BlockByrefInfos.end())
2075 return it->second;
John McCall73064872011-03-31 01:59:53 +00002076
John McCall7f416cc2015-09-08 08:05:57 +00002077 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002078 llvm::StructType::create(getLLVMContext(),
2079 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002080
John McCall7f416cc2015-09-08 08:05:57 +00002081 QualType Ty = D->getType();
2082
2083 CharUnits size;
2084 SmallVector<llvm::Type *, 8> types;
2085
John McCall73064872011-03-31 01:59:53 +00002086 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002087 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002088 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002089
2090 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002091 types.push_back(llvm::PointerType::getUnqual(byrefType));
2092 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002093
2094 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002095 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002096 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002097
2098 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002099 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002100 size += CharUnits::fromQuantity(4);
2101
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002102 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002103 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2104 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002105 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002106 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002107 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002108
2109 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002110 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002111 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002112 }
John McCall7f416cc2015-09-08 08:05:57 +00002113
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002114 bool HasByrefExtendedLayout = false;
2115 Qualifiers::ObjCLifetime Lifetime;
2116 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002117 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002118 /// void *__byref_variable_layout;
2119 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002120 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002121 }
2122
2123 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002124 llvm::Type *varTy = ConvertTypeForMem(Ty);
2125
2126 bool packed = false;
2127 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002128 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002129
2130 // We may have to insert padding.
2131 if (varOffset != size) {
2132 llvm::Type *paddingTy =
2133 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2134
2135 types.push_back(paddingTy);
2136 size = varOffset;
2137
2138 // Conversely, we might have to prevent LLVM from inserting padding.
2139 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2140 > varAlign.getQuantity()) {
2141 packed = true;
2142 }
2143 types.push_back(varTy);
2144
2145 byrefType->setBody(types, packed);
2146
2147 BlockByrefInfo info;
2148 info.Type = byrefType;
2149 info.FieldIndex = types.size() - 1;
2150 info.FieldOffset = varOffset;
2151 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2152
2153 auto pair = BlockByrefInfos.insert({D, info});
2154 assert(pair.second && "info was inserted recursively?");
2155 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002156}
2157
2158/// Initialize the structural components of a __block variable, i.e.
2159/// everything but the actual object.
2160void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002161 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002162 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002163
John McCallf9b056b2011-03-31 08:03:29 +00002164 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002165 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002166 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2167
2168 unsigned nextHeaderIndex = 0;
2169 CharUnits nextHeaderOffset;
2170 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2171 const Twine &name) {
2172 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2173 nextHeaderOffset, name);
2174 Builder.CreateStore(value, fieldAddr);
2175
2176 nextHeaderIndex++;
2177 nextHeaderOffset += fieldSize;
2178 };
John McCallf9b056b2011-03-31 08:03:29 +00002179
2180 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002181 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002182
2183 const VarDecl &D = *emission.Variable;
2184 QualType type = D.getType();
2185
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002186 bool HasByrefExtendedLayout;
2187 Qualifiers::ObjCLifetime ByrefLifetime;
2188 bool ByRefHasLifetime =
2189 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002190
John McCallf9b056b2011-03-31 08:03:29 +00002191 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002192
2193 // Initialize the 'isa', which is just 0 or 1.
2194 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002195 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002196 isa = 1;
2197 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002198 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002199
2200 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002201 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002202
2203 // Blocks ABI:
2204 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002205 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002206 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002207 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2208 if (ByRefHasLifetime) {
2209 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2210 else switch (ByrefLifetime) {
2211 case Qualifiers::OCL_Strong:
2212 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2213 break;
2214 case Qualifiers::OCL_Weak:
2215 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2216 break;
2217 case Qualifiers::OCL_ExplicitNone:
2218 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2219 break;
2220 case Qualifiers::OCL_None:
2221 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2222 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2223 break;
2224 default:
2225 break;
2226 }
2227 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2228 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2229 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2230 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2231 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2232 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2233 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2234 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2235 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2236 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2237 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2238 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2239 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2240 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2241 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2242 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2243 }
2244 printf("\n");
2245 }
2246 }
John McCall7f416cc2015-09-08 08:05:57 +00002247 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2248 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002249
John McCallf9b056b2011-03-31 08:03:29 +00002250 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2251 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002252 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002253
John McCallf9b056b2011-03-31 08:03:29 +00002254 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002255 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2256 "byref.copyHelper");
2257 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2258 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002259 }
John McCall7f416cc2015-09-08 08:05:57 +00002260
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002261 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002262 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2263 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002264 }
John McCall73064872011-03-31 01:59:53 +00002265}
2266
John McCallad7c5c12011-02-08 08:22:06 +00002267void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002268 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002269 llvm::Value *args[] = {
2270 Builder.CreateBitCast(V, Int8PtrTy),
2271 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2272 };
2273 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002274}
John McCall73064872011-03-31 01:59:53 +00002275
2276namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002277 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002278 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002279 llvm::Value *Addr;
2280 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2281
Craig Topper4f12f102014-03-12 06:41:41 +00002282 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002283 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002284 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2285 }
2286 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002287} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002288
2289/// Enter a cleanup to destroy a __block variable. Note that this
2290/// cleanup should be a no-op if the variable hasn't left the stack
2291/// yet; if a cleanup is required for the variable itself, that needs
2292/// to be done externally.
2293void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2294 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002295 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002296 return;
2297
John McCall7f416cc2015-09-08 08:05:57 +00002298 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2299 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002300}
John McCall7959fee2011-09-09 20:41:01 +00002301
2302/// Adjust the declaration of something from the blocks API.
2303static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2304 llvm::Constant *C) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002305 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002306
2307 if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
2308 IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
2309 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2310 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2311
Saleem Abdulrasool7bae9ad2016-06-03 23:26:30 +00002312 assert((isa<llvm::Function>(C->stripPointerCasts()) ||
2313 isa<llvm::GlobalVariable>(C->stripPointerCasts())) &&
2314 "expected Function or GlobalVariable");
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002315
2316 const NamedDecl *ND = nullptr;
2317 for (const auto &Result : DC->lookup(&II))
2318 if ((ND = dyn_cast<FunctionDecl>(Result)) ||
2319 (ND = dyn_cast<VarDecl>(Result)))
2320 break;
2321
2322 // TODO: support static blocks runtime
2323 if (GV->isDeclaration() && (!ND || !ND->hasAttr<DLLExportAttr>())) {
2324 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2325 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2326 } else {
2327 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2328 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2329 }
2330 }
2331
2332 if (!CGM.getLangOpts().BlocksRuntimeOptional)
2333 return;
2334
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002335 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002336 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2337}
2338
2339llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2340 if (BlockObjectDispose)
2341 return BlockObjectDispose;
2342
2343 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2344 llvm::FunctionType *fty
2345 = llvm::FunctionType::get(VoidTy, args, false);
2346 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2347 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2348 return BlockObjectDispose;
2349}
2350
2351llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2352 if (BlockObjectAssign)
2353 return BlockObjectAssign;
2354
2355 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2356 llvm::FunctionType *fty
2357 = llvm::FunctionType::get(VoidTy, args, false);
2358 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2359 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2360 return BlockObjectAssign;
2361}
2362
2363llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2364 if (NSConcreteGlobalBlock)
2365 return NSConcreteGlobalBlock;
2366
2367 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002368 Int8PtrTy->getPointerTo(),
2369 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002370 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2371 return NSConcreteGlobalBlock;
2372}
2373
2374llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2375 if (NSConcreteStackBlock)
2376 return NSConcreteStackBlock;
2377
2378 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002379 Int8PtrTy->getPointerTo(),
2380 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002381 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
Saleem Abdulrasool442b88b2016-05-28 19:41:35 +00002382 return NSConcreteStackBlock;
John McCall7959fee2011-09-09 20:41:01 +00002383}