blob: a74294e7d624bd7afbf3bd3695beb1750c0ea519 [file] [log] [blame]
Hans Wennborgdcfba332015-10-06 23:40:43 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations ---------*- C++ -*-===//
Anders Carlsson2437cbf2009-02-12 00:39:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
John McCallad7c5c12011-02-08 08:22:06 +000014#include "CGBlocks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
Mike Stump692c6e32009-03-20 21:53:12 +000019#include "clang/AST/DeclObjC.h"
Benjamin Kramer9e2e1c92010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Module.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000024#include <algorithm>
Fariborz Jahanian983ae492012-11-14 17:43:08 +000025#include <cstdio>
Torok Edwindb714922009-08-24 13:25:12 +000026
Anders Carlsson2437cbf2009-02-12 00:39:25 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall08ef4662011-11-10 08:15:53 +000030CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
31 : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
Fariborz Jahanian23290b02012-11-01 18:32:55 +000032 HasCXXObject(false), UsesStret(false), HasCapturedVariableLayout(false),
John McCall7f416cc2015-09-08 08:05:57 +000033 LocalAddress(Address::invalid()), StructureType(nullptr), Block(block),
Craig Topper8a13c412014-05-21 05:09:00 +000034 DominatingIP(nullptr) {
35
John McCall08ef4662011-11-10 08:15:53 +000036 // Skip asm prefix, if any. 'name' is usually taken directly from
37 // the mangled name of the enclosing function.
38 if (!name.empty() && name[0] == '\01')
39 name = name.substr(1);
John McCall9d42f0f2010-05-21 04:11:14 +000040}
41
John McCallf9b056b2011-03-31 08:03:29 +000042// Anchor the vtable to this translation unit.
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000043BlockByrefHelpers::~BlockByrefHelpers() {}
John McCallf9b056b2011-03-31 08:03:29 +000044
John McCall351762c2011-02-07 10:33:21 +000045/// Build the given block as a global block.
46static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
47 const CGBlockInfo &blockInfo,
48 llvm::Constant *blockFn);
John McCall9d42f0f2010-05-21 04:11:14 +000049
John McCall351762c2011-02-07 10:33:21 +000050/// Build the helper function to copy a block.
51static llvm::Constant *buildCopyHelper(CodeGenModule &CGM,
52 const CGBlockInfo &blockInfo) {
53 return CodeGenFunction(CGM).GenerateCopyHelperFunction(blockInfo);
54}
55
Alp Tokerf6a24ce2013-12-05 16:25:25 +000056/// Build the helper function to dispose of a block.
John McCall351762c2011-02-07 10:33:21 +000057static llvm::Constant *buildDisposeHelper(CodeGenModule &CGM,
58 const CGBlockInfo &blockInfo) {
59 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(blockInfo);
60}
61
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000062/// buildBlockDescriptor - Build the block descriptor meta-data for a block.
63/// buildBlockDescriptor is accessed from 5th field of the Block_literal
64/// meta-data and contains stationary information about the block literal.
65/// Its definition will have 4 (or optinally 6) words.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000066/// \code
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000067/// struct Block_descriptor {
68/// unsigned long reserved;
69/// unsigned long size; // size of Block_literal metadata in bytes.
70/// void *copy_func_helper_decl; // optional copy helper.
71/// void *destroy_func_decl; // optioanl destructor helper.
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000072/// void *block_method_encoding_address; // @encode for block literal signature.
Fariborz Jahanianbf7bf292012-10-25 18:06:53 +000073/// void *block_layout_info; // encoding of captured block variables.
74/// };
Dmitri Gribenko6c96ba22013-05-08 23:09:44 +000075/// \endcode
John McCall351762c2011-02-07 10:33:21 +000076static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
77 const CGBlockInfo &blockInfo) {
78 ASTContext &C = CGM.getContext();
79
Chris Lattner2192fe52011-07-18 04:24:23 +000080 llvm::Type *ulong = CGM.getTypes().ConvertType(C.UnsignedLongTy);
Hans Wennborgdcfba332015-10-06 23:40:43 +000081 llvm::Type *i8p = nullptr;
Pekka Jaaskelainenab751a82014-08-14 09:37:50 +000082 if (CGM.getLangOpts().OpenCL)
83 i8p =
84 llvm::Type::getInt8PtrTy(
85 CGM.getLLVMContext(), C.getTargetAddressSpace(LangAS::opencl_constant));
86 else
87 i8p = CGM.getTypes().ConvertType(C.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +000088
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 SmallVector<llvm::Constant*, 6> elements;
Mike Stump85284ba2009-02-13 16:19:19 +000090
91 // reserved
John McCall351762c2011-02-07 10:33:21 +000092 elements.push_back(llvm::ConstantInt::get(ulong, 0));
Mike Stump85284ba2009-02-13 16:19:19 +000093
94 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000095 // FIXME: What is the right way to say this doesn't fit? We should give
96 // a user diagnostic in that case. Better fix would be to change the
97 // API to size_t.
John McCall351762c2011-02-07 10:33:21 +000098 elements.push_back(llvm::ConstantInt::get(ulong,
99 blockInfo.BlockSize.getQuantity()));
Mike Stump85284ba2009-02-13 16:19:19 +0000100
John McCall351762c2011-02-07 10:33:21 +0000101 // Optional copy/dispose helpers.
102 if (blockInfo.NeedsCopyDispose) {
Mike Stump85284ba2009-02-13 16:19:19 +0000103 // copy_func_helper_decl
John McCall351762c2011-02-07 10:33:21 +0000104 elements.push_back(buildCopyHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000105
106 // destroy_func_decl
John McCall351762c2011-02-07 10:33:21 +0000107 elements.push_back(buildDisposeHelper(CGM, blockInfo));
Mike Stump85284ba2009-02-13 16:19:19 +0000108 }
109
John McCall351762c2011-02-07 10:33:21 +0000110 // Signature. Mandatory ObjC-style method descriptor @encode sequence.
111 std::string typeAtEncoding =
112 CGM.getContext().getObjCEncodingForBlock(blockInfo.getBlockExpr());
113 elements.push_back(llvm::ConstantExpr::getBitCast(
John McCall7f416cc2015-09-08 08:05:57 +0000114 CGM.GetAddrOfConstantCString(typeAtEncoding).getPointer(), i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000115
John McCall351762c2011-02-07 10:33:21 +0000116 // GC layout.
Fariborz Jahanian0c58ce92012-10-27 21:10:38 +0000117 if (C.getLangOpts().ObjC1) {
118 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
119 elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockInfo));
120 else
121 elements.push_back(CGM.getObjCRuntime().BuildRCBlockLayout(CGM, blockInfo));
122 }
John McCall351762c2011-02-07 10:33:21 +0000123 else
124 elements.push_back(llvm::Constant::getNullValue(i8p));
Blaine Garstfc83aa02010-02-23 21:51:17 +0000125
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000126 llvm::Constant *init = llvm::ConstantStruct::getAnon(elements);
Mike Stump85284ba2009-02-13 16:19:19 +0000127
John McCall351762c2011-02-07 10:33:21 +0000128 llvm::GlobalVariable *global =
129 new llvm::GlobalVariable(CGM.getModule(), init->getType(), true,
130 llvm::GlobalValue::InternalLinkage,
131 init, "__block_descriptor_tmp");
Mike Stump85284ba2009-02-13 16:19:19 +0000132
John McCall351762c2011-02-07 10:33:21 +0000133 return llvm::ConstantExpr::getBitCast(global, CGM.getBlockDescriptorType());
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000134}
135
John McCall351762c2011-02-07 10:33:21 +0000136/*
137 Purely notional variadic template describing the layout of a block.
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000138
John McCall351762c2011-02-07 10:33:21 +0000139 template <class _ResultType, class... _ParamTypes, class... _CaptureTypes>
140 struct Block_literal {
141 /// Initialized to one of:
142 /// extern void *_NSConcreteStackBlock[];
143 /// extern void *_NSConcreteGlobalBlock[];
144 ///
145 /// In theory, we could start one off malloc'ed by setting
146 /// BLOCK_NEEDS_FREE, giving it a refcount of 1, and using
147 /// this isa:
148 /// extern void *_NSConcreteMallocBlock[];
149 struct objc_class *isa;
Mike Stump4446dcf2009-03-05 08:32:30 +0000150
John McCall351762c2011-02-07 10:33:21 +0000151 /// These are the flags (with corresponding bit number) that the
152 /// compiler is actually supposed to know about.
153 /// 25. BLOCK_HAS_COPY_DISPOSE - indicates that the block
154 /// descriptor provides copy and dispose helper functions
155 /// 26. BLOCK_HAS_CXX_OBJ - indicates that there's a captured
156 /// object with a nontrivial destructor or copy constructor
157 /// 28. BLOCK_IS_GLOBAL - indicates that the block is allocated
158 /// as global memory
159 /// 29. BLOCK_USE_STRET - indicates that the block function
160 /// uses stret, which objc_msgSend needs to know about
161 /// 30. BLOCK_HAS_SIGNATURE - indicates that the block has an
162 /// @encoded signature string
163 /// And we're not supposed to manipulate these:
164 /// 24. BLOCK_NEEDS_FREE - indicates that the block has been moved
165 /// to malloc'ed memory
166 /// 27. BLOCK_IS_GC - indicates that the block has been moved to
167 /// to GC-allocated memory
168 /// Additionally, the bottom 16 bits are a reference count which
169 /// should be zero on the stack.
170 int flags;
David Chisnall950a9512009-11-17 19:33:30 +0000171
John McCall351762c2011-02-07 10:33:21 +0000172 /// Reserved; should be zero-initialized.
173 int reserved;
David Chisnall950a9512009-11-17 19:33:30 +0000174
John McCall351762c2011-02-07 10:33:21 +0000175 /// Function pointer generated from block literal.
176 _ResultType (*invoke)(Block_literal *, _ParamTypes...);
Mike Stump85284ba2009-02-13 16:19:19 +0000177
John McCall351762c2011-02-07 10:33:21 +0000178 /// Block description metadata generated from block literal.
179 struct Block_descriptor *block_descriptor;
John McCall3882ace2011-01-05 12:14:39 +0000180
John McCall351762c2011-02-07 10:33:21 +0000181 /// Captured values follow.
182 _CapturesTypes captures...;
183 };
184 */
David Chisnall950a9512009-11-17 19:33:30 +0000185
John McCall351762c2011-02-07 10:33:21 +0000186/// The number of fields in a block header.
187const unsigned BlockHeaderSize = 5;
Mike Stump4446dcf2009-03-05 08:32:30 +0000188
John McCall351762c2011-02-07 10:33:21 +0000189namespace {
190 /// A chunk of data that we actually have to capture in the block.
191 struct BlockLayoutChunk {
192 CharUnits Alignment;
193 CharUnits Size;
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000194 Qualifiers::ObjCLifetime Lifetime;
John McCall351762c2011-02-07 10:33:21 +0000195 const BlockDecl::Capture *Capture; // null for 'this'
Jay Foad7c57be32011-07-11 09:56:20 +0000196 llvm::Type *Type;
Mike Stump85284ba2009-02-13 16:19:19 +0000197
John McCall351762c2011-02-07 10:33:21 +0000198 BlockLayoutChunk(CharUnits align, CharUnits size,
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000199 Qualifiers::ObjCLifetime lifetime,
John McCall351762c2011-02-07 10:33:21 +0000200 const BlockDecl::Capture *capture,
Jay Foad7c57be32011-07-11 09:56:20 +0000201 llvm::Type *type)
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000202 : Alignment(align), Size(size), Lifetime(lifetime),
203 Capture(capture), Type(type) {}
Mike Stump85284ba2009-02-13 16:19:19 +0000204
John McCall351762c2011-02-07 10:33:21 +0000205 /// Tell the block info that this chunk has the given field index.
John McCall7f416cc2015-09-08 08:05:57 +0000206 void setIndex(CGBlockInfo &info, unsigned index, CharUnits offset) {
207 if (!Capture) {
John McCall351762c2011-02-07 10:33:21 +0000208 info.CXXThisIndex = index;
John McCall7f416cc2015-09-08 08:05:57 +0000209 info.CXXThisOffset = offset;
210 } else {
211 info.Captures.insert({Capture->getVariable(),
212 CGBlockInfo::Capture::makeIndex(index, offset)});
213 }
John McCall87fe5d52010-05-20 01:18:31 +0000214 }
John McCall351762c2011-02-07 10:33:21 +0000215 };
Mike Stumpd6ef62f2009-03-06 18:42:23 +0000216
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000217 /// Order by 1) all __strong together 2) next, all byfref together 3) next,
218 /// all __weak together. Preserve descending alignment in all situations.
John McCall351762c2011-02-07 10:33:21 +0000219 bool operator<(const BlockLayoutChunk &left, const BlockLayoutChunk &right) {
John McCall7f416cc2015-09-08 08:05:57 +0000220 if (left.Alignment != right.Alignment)
221 return left.Alignment > right.Alignment;
222
223 auto getPrefOrder = [](const BlockLayoutChunk &chunk) {
John McCall9c52b282015-09-11 22:00:51 +0000224 if (chunk.Capture && chunk.Capture->isByRef())
John McCall7f416cc2015-09-08 08:05:57 +0000225 return 1;
226 if (chunk.Lifetime == Qualifiers::OCL_Strong)
227 return 0;
228 if (chunk.Lifetime == Qualifiers::OCL_Weak)
229 return 2;
230 return 3;
231 };
232
233 return getPrefOrder(left) < getPrefOrder(right);
John McCall351762c2011-02-07 10:33:21 +0000234 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000235} // end anonymous namespace
John McCall351762c2011-02-07 10:33:21 +0000236
John McCallb0a3ecb2011-02-08 03:07:00 +0000237/// Determines if the given type is safe for constant capture in C++.
238static bool isSafeForCXXConstantCapture(QualType type) {
239 const RecordType *recordType =
240 type->getBaseElementTypeUnsafe()->getAs<RecordType>();
241
242 // Only records can be unsafe.
243 if (!recordType) return true;
244
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000245 const auto *record = cast<CXXRecordDecl>(recordType->getDecl());
John McCallb0a3ecb2011-02-08 03:07:00 +0000246
247 // Maintain semantics for classes with non-trivial dtors or copy ctors.
248 if (!record->hasTrivialDestructor()) return false;
Richard Smith16488472012-11-16 00:53:38 +0000249 if (record->hasNonTrivialCopyConstructor()) return false;
John McCallb0a3ecb2011-02-08 03:07:00 +0000250
251 // Otherwise, we just have to make sure there aren't any mutable
252 // fields that might have changed since initialization.
Douglas Gregor61226d32011-05-13 01:05:07 +0000253 return !record->hasMutableFields();
John McCallb0a3ecb2011-02-08 03:07:00 +0000254}
255
John McCall351762c2011-02-07 10:33:21 +0000256/// It is illegal to modify a const object after initialization.
257/// Therefore, if a const object has a constant initializer, we don't
258/// actually need to keep storage for it in the block; we'll just
259/// rematerialize it at the start of the block function. This is
260/// acceptable because we make no promises about address stability of
261/// captured variables.
262static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
Richard Smithdafff942012-01-14 04:30:29 +0000263 CodeGenFunction *CGF,
John McCall351762c2011-02-07 10:33:21 +0000264 const VarDecl *var) {
265 QualType type = var->getType();
266
267 // We can only do this if the variable is const.
Craig Topper8a13c412014-05-21 05:09:00 +0000268 if (!type.isConstQualified()) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000269
John McCallb0a3ecb2011-02-08 03:07:00 +0000270 // Furthermore, in C++ we have to worry about mutable fields:
271 // C++ [dcl.type.cv]p4:
272 // Except that any class member declared mutable can be
273 // modified, any attempt to modify a const object during its
274 // lifetime results in undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000275 if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
Craig Topper8a13c412014-05-21 05:09:00 +0000276 return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000277
278 // If the variable doesn't have any initializer (shouldn't this be
279 // invalid?), it's not clear what we should do. Maybe capture as
280 // zero?
281 const Expr *init = var->getInit();
Craig Topper8a13c412014-05-21 05:09:00 +0000282 if (!init) return nullptr;
John McCall351762c2011-02-07 10:33:21 +0000283
Richard Smithdafff942012-01-14 04:30:29 +0000284 return CGM.EmitConstantInit(*var, CGF);
John McCall351762c2011-02-07 10:33:21 +0000285}
286
287/// Get the low bit of a nonzero character count. This is the
288/// alignment of the nth byte if the 0th byte is universally aligned.
289static CharUnits getLowBit(CharUnits v) {
290 return CharUnits::fromQuantity(v.getQuantity() & (~v.getQuantity() + 1));
291}
292
293static void initializeForBlockHeader(CodeGenModule &CGM, CGBlockInfo &info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000294 SmallVectorImpl<llvm::Type*> &elementTypes) {
John McCall7f416cc2015-09-08 08:05:57 +0000295 // The header is basically 'struct { void *; int; int; void *; void *; }'.
296 // Assert that that struct is packed.
297 assert(CGM.getIntSize() <= CGM.getPointerSize());
298 assert(CGM.getIntAlign() <= CGM.getPointerAlign());
299 assert((2 * CGM.getIntSize()).isMultipleOf(CGM.getPointerAlign()));
John McCall351762c2011-02-07 10:33:21 +0000300
John McCall7f416cc2015-09-08 08:05:57 +0000301 info.BlockAlign = CGM.getPointerAlign();
302 info.BlockSize = 3 * CGM.getPointerSize() + 2 * CGM.getIntSize();
John McCall351762c2011-02-07 10:33:21 +0000303
304 assert(elementTypes.empty());
John McCall7f416cc2015-09-08 08:05:57 +0000305 elementTypes.push_back(CGM.VoidPtrTy);
306 elementTypes.push_back(CGM.IntTy);
307 elementTypes.push_back(CGM.IntTy);
308 elementTypes.push_back(CGM.VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000309 elementTypes.push_back(CGM.getBlockDescriptorType());
310
311 assert(elementTypes.size() == BlockHeaderSize);
312}
313
314/// Compute the layout of the given block. Attempts to lay the block
315/// out with minimal space requirements.
Richard Smithdafff942012-01-14 04:30:29 +0000316static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
317 CGBlockInfo &info) {
John McCall351762c2011-02-07 10:33:21 +0000318 ASTContext &C = CGM.getContext();
319 const BlockDecl *block = info.getBlockDecl();
320
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 SmallVector<llvm::Type*, 8> elementTypes;
John McCall351762c2011-02-07 10:33:21 +0000322 initializeForBlockHeader(CGM, info, elementTypes);
323
324 if (!block->hasCaptures()) {
325 info.StructureType =
326 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
327 info.CanBeGlobal = true;
328 return;
Mike Stump85284ba2009-02-13 16:19:19 +0000329 }
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000330 else if (C.getLangOpts().ObjC1 &&
331 CGM.getLangOpts().getGC() == LangOptions::NonGC)
332 info.HasCapturedVariableLayout = true;
333
John McCall351762c2011-02-07 10:33:21 +0000334 // Collect the layout chunks.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000335 SmallVector<BlockLayoutChunk, 16> layout;
John McCall351762c2011-02-07 10:33:21 +0000336 layout.reserve(block->capturesCXXThis() +
337 (block->capture_end() - block->capture_begin()));
338
339 CharUnits maxFieldAlign;
340
341 // First, 'this'.
342 if (block->capturesCXXThis()) {
Eli Friedmanc6036aa2013-07-12 22:05:26 +0000343 assert(CGF && CGF->CurFuncDecl && isa<CXXMethodDecl>(CGF->CurFuncDecl) &&
344 "Can't capture 'this' outside a method");
345 QualType thisType = cast<CXXMethodDecl>(CGF->CurFuncDecl)->getThisType(C);
John McCall351762c2011-02-07 10:33:21 +0000346
John McCall7f416cc2015-09-08 08:05:57 +0000347 // Theoretically, this could be in a different address space, so
348 // don't assume standard pointer size/align.
Jay Foad7c57be32011-07-11 09:56:20 +0000349 llvm::Type *llvmType = CGM.getTypes().ConvertType(thisType);
John McCall351762c2011-02-07 10:33:21 +0000350 std::pair<CharUnits,CharUnits> tinfo
351 = CGM.getContext().getTypeInfoInChars(thisType);
352 maxFieldAlign = std::max(maxFieldAlign, tinfo.second);
353
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000354 layout.push_back(BlockLayoutChunk(tinfo.second, tinfo.first,
355 Qualifiers::OCL_None,
Craig Topper8a13c412014-05-21 05:09:00 +0000356 nullptr, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000357 }
358
359 // Next, all the block captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000360 for (const auto &CI : block->captures()) {
361 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000362
Aaron Ballman9371dd22014-03-14 18:34:04 +0000363 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +0000364 // We have to copy/dispose of the __block reference.
365 info.NeedsCopyDispose = true;
366
John McCall351762c2011-02-07 10:33:21 +0000367 // Just use void* instead of a pointer to the byref type.
John McCall7f416cc2015-09-08 08:05:57 +0000368 CharUnits align = CGM.getPointerAlign();
369 maxFieldAlign = std::max(maxFieldAlign, align);
John McCall351762c2011-02-07 10:33:21 +0000370
John McCall7f416cc2015-09-08 08:05:57 +0000371 layout.push_back(BlockLayoutChunk(align, CGM.getPointerSize(),
372 Qualifiers::OCL_None, &CI,
373 CGM.VoidPtrTy));
John McCall351762c2011-02-07 10:33:21 +0000374 continue;
375 }
376
377 // Otherwise, build a layout chunk with the size and alignment of
378 // the declaration.
Richard Smithdafff942012-01-14 04:30:29 +0000379 if (llvm::Constant *constant = tryCaptureAsConstant(CGM, CGF, variable)) {
John McCall351762c2011-02-07 10:33:21 +0000380 info.Captures[variable] = CGBlockInfo::Capture::makeConstant(constant);
381 continue;
382 }
383
John McCall31168b02011-06-15 23:02:42 +0000384 // If we have a lifetime qualifier, honor it for capture purposes.
385 // That includes *not* copying it if it's __unsafe_unretained.
Fariborz Jahanianc8892052013-01-17 00:25:06 +0000386 Qualifiers::ObjCLifetime lifetime =
387 variable->getType().getObjCLifetime();
388 if (lifetime) {
John McCall31168b02011-06-15 23:02:42 +0000389 switch (lifetime) {
390 case Qualifiers::OCL_None: llvm_unreachable("impossible");
391 case Qualifiers::OCL_ExplicitNone:
392 case Qualifiers::OCL_Autoreleasing:
393 break;
John McCall351762c2011-02-07 10:33:21 +0000394
John McCall31168b02011-06-15 23:02:42 +0000395 case Qualifiers::OCL_Strong:
396 case Qualifiers::OCL_Weak:
397 info.NeedsCopyDispose = true;
398 }
399
400 // Block pointers require copy/dispose. So do Objective-C pointers.
401 } else if (variable->getType()->isObjCRetainableType()) {
John McCall00b2bbb2015-11-19 02:28:03 +0000402 // But honor the inert __unsafe_unretained qualifier, which doesn't
403 // actually make it into the type system.
404 if (variable->getType()->isObjCInertUnsafeUnretainedType()) {
405 lifetime = Qualifiers::OCL_ExplicitNone;
406 } else {
407 info.NeedsCopyDispose = true;
408 // used for mrr below.
409 lifetime = Qualifiers::OCL_Strong;
410 }
John McCall351762c2011-02-07 10:33:21 +0000411
412 // So do types that require non-trivial copy construction.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000413 } else if (CI.hasCopyExpr()) {
John McCall351762c2011-02-07 10:33:21 +0000414 info.NeedsCopyDispose = true;
415 info.HasCXXObject = true;
416
417 // And so do types with destructors.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000418 } else if (CGM.getLangOpts().CPlusPlus) {
John McCall351762c2011-02-07 10:33:21 +0000419 if (const CXXRecordDecl *record =
420 variable->getType()->getAsCXXRecordDecl()) {
421 if (!record->hasTrivialDestructor()) {
422 info.HasCXXObject = true;
423 info.NeedsCopyDispose = true;
424 }
425 }
426 }
427
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000428 QualType VT = variable->getType();
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000429 CharUnits size = C.getTypeSizeInChars(VT);
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000430 CharUnits align = C.getDeclAlign(variable);
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000431
John McCall351762c2011-02-07 10:33:21 +0000432 maxFieldAlign = std::max(maxFieldAlign, align);
433
Jay Foad7c57be32011-07-11 09:56:20 +0000434 llvm::Type *llvmType =
Fariborz Jahanianf0cda632011-10-31 23:44:33 +0000435 CGM.getTypes().ConvertTypeForMem(VT);
436
Aaron Ballman9371dd22014-03-14 18:34:04 +0000437 layout.push_back(BlockLayoutChunk(align, size, lifetime, &CI, llvmType));
John McCall351762c2011-02-07 10:33:21 +0000438 }
439
440 // If that was everything, we're done here.
441 if (layout.empty()) {
442 info.StructureType =
443 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
444 info.CanBeGlobal = true;
445 return;
446 }
447
448 // Sort the layout by alignment. We have to use a stable sort here
449 // to get reproducible results. There should probably be an
450 // llvm::array_pod_stable_sort.
451 std::stable_sort(layout.begin(), layout.end());
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000452
453 // Needed for blocks layout info.
454 info.BlockHeaderForcedGapOffset = info.BlockSize;
455 info.BlockHeaderForcedGapSize = CharUnits::Zero();
456
John McCall351762c2011-02-07 10:33:21 +0000457 CharUnits &blockSize = info.BlockSize;
458 info.BlockAlign = std::max(maxFieldAlign, info.BlockAlign);
459
460 // Assuming that the first byte in the header is maximally aligned,
461 // get the alignment of the first byte following the header.
462 CharUnits endAlign = getLowBit(blockSize);
463
464 // If the end of the header isn't satisfactorily aligned for the
465 // maximum thing, look for things that are okay with the header-end
466 // alignment, and keep appending them until we get something that's
467 // aligned right. This algorithm is only guaranteed optimal if
468 // that condition is satisfied at some point; otherwise we can get
469 // things like:
470 // header // next byte has alignment 4
471 // something_with_size_5; // next byte has alignment 1
472 // something_with_alignment_8;
473 // which has 7 bytes of padding, as opposed to the naive solution
474 // which might have less (?).
475 if (endAlign < maxFieldAlign) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000476 SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000477 li = layout.begin() + 1, le = layout.end();
478
479 // Look for something that the header end is already
480 // satisfactorily aligned for.
481 for (; li != le && endAlign < li->Alignment; ++li)
482 ;
483
484 // If we found something that's naturally aligned for the end of
485 // the header, keep adding things...
486 if (li != le) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 SmallVectorImpl<BlockLayoutChunk>::iterator first = li;
John McCall351762c2011-02-07 10:33:21 +0000488 for (; li != le; ++li) {
489 assert(endAlign >= li->Alignment);
490
John McCall7f416cc2015-09-08 08:05:57 +0000491 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000492 elementTypes.push_back(li->Type);
493 blockSize += li->Size;
494 endAlign = getLowBit(blockSize);
495
496 // ...until we get to the alignment of the maximum field.
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000497 if (endAlign >= maxFieldAlign) {
John McCall351762c2011-02-07 10:33:21 +0000498 break;
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000499 }
John McCall351762c2011-02-07 10:33:21 +0000500 }
John McCall351762c2011-02-07 10:33:21 +0000501 // Don't re-append everything we just appended.
502 layout.erase(first, li);
503 }
504 }
505
John McCallac0350a2012-04-26 21:14:42 +0000506 assert(endAlign == getLowBit(blockSize));
Fariborz Jahanian4cf177e2012-12-04 17:20:57 +0000507
John McCall351762c2011-02-07 10:33:21 +0000508 // At this point, we just have to add padding if the end align still
509 // isn't aligned right.
510 if (endAlign < maxFieldAlign) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000511 CharUnits newBlockSize = blockSize.alignTo(maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000512 CharUnits padding = newBlockSize - blockSize;
John McCall351762c2011-02-07 10:33:21 +0000513
John McCall7f416cc2015-09-08 08:05:57 +0000514 // If we haven't yet added any fields, remember that there was an
515 // initial gap; this need to go into the block layout bit map.
516 if (blockSize == info.BlockHeaderForcedGapOffset) {
517 info.BlockHeaderForcedGapSize = padding;
518 }
519
John McCalle3dc1702011-02-15 09:22:45 +0000520 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
521 padding.getQuantity()));
John McCallac0350a2012-04-26 21:14:42 +0000522 blockSize = newBlockSize;
John McCall1db0a2f2012-05-01 20:28:00 +0000523 endAlign = getLowBit(blockSize); // might be > maxFieldAlign
John McCall351762c2011-02-07 10:33:21 +0000524 }
525
John McCall1db0a2f2012-05-01 20:28:00 +0000526 assert(endAlign >= maxFieldAlign);
John McCallac0350a2012-04-26 21:14:42 +0000527 assert(endAlign == getLowBit(blockSize));
John McCall351762c2011-02-07 10:33:21 +0000528 // Slam everything else on now. This works because they have
529 // strictly decreasing alignment and we expect that size is always a
530 // multiple of alignment.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000531 for (SmallVectorImpl<BlockLayoutChunk>::iterator
John McCall351762c2011-02-07 10:33:21 +0000532 li = layout.begin(), le = layout.end(); li != le; ++li) {
Fariborz Jahanian9c56fc92014-08-12 15:51:49 +0000533 if (endAlign < li->Alignment) {
534 // size may not be multiple of alignment. This can only happen with
535 // an over-aligned variable. We will be adding a padding field to
536 // make the size be multiple of alignment.
537 CharUnits padding = li->Alignment - endAlign;
538 elementTypes.push_back(llvm::ArrayType::get(CGM.Int8Ty,
539 padding.getQuantity()));
540 blockSize += padding;
541 endAlign = getLowBit(blockSize);
542 }
John McCall351762c2011-02-07 10:33:21 +0000543 assert(endAlign >= li->Alignment);
John McCall7f416cc2015-09-08 08:05:57 +0000544 li->setIndex(info, elementTypes.size(), blockSize);
John McCall351762c2011-02-07 10:33:21 +0000545 elementTypes.push_back(li->Type);
546 blockSize += li->Size;
547 endAlign = getLowBit(blockSize);
548 }
549
550 info.StructureType =
551 llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
552}
553
John McCall08ef4662011-11-10 08:15:53 +0000554/// Enter the scope of a block. This should be run at the entrance to
555/// a full-expression so that the block's cleanups are pushed at the
556/// right place in the stack.
557static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
John McCall8c38d352012-04-13 18:44:05 +0000558 assert(CGF.HaveInsertPoint());
559
John McCall08ef4662011-11-10 08:15:53 +0000560 // Allocate the block info and place it at the head of the list.
561 CGBlockInfo &blockInfo =
562 *new CGBlockInfo(block, CGF.CurFn->getName());
563 blockInfo.NextBlockInfo = CGF.FirstBlockInfo;
564 CGF.FirstBlockInfo = &blockInfo;
565
566 // Compute information about the layout, etc., of this block,
567 // pushing cleanups as necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000568 computeBlockInfo(CGF.CGM, &CGF, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000569
570 // Nothing else to do if it can be global.
571 if (blockInfo.CanBeGlobal) return;
572
573 // Make the allocation for the block.
John McCall7f416cc2015-09-08 08:05:57 +0000574 blockInfo.LocalAddress = CGF.CreateTempAlloca(blockInfo.StructureType,
575 blockInfo.BlockAlign, "block");
John McCall08ef4662011-11-10 08:15:53 +0000576
577 // If there are cleanups to emit, enter them (but inactive).
578 if (!blockInfo.NeedsCopyDispose) return;
579
580 // Walk through the captures (in order) and find the ones not
581 // captured by constant.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000582 for (const auto &CI : block->captures()) {
John McCall08ef4662011-11-10 08:15:53 +0000583 // Ignore __block captures; there's nothing special in the
584 // on-stack block that we need to do for them.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000585 if (CI.isByRef()) continue;
John McCall08ef4662011-11-10 08:15:53 +0000586
587 // Ignore variables that are constant-captured.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000588 const VarDecl *variable = CI.getVariable();
John McCall08ef4662011-11-10 08:15:53 +0000589 CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
590 if (capture.isConstant()) continue;
591
592 // Ignore objects that aren't destructed.
593 QualType::DestructionKind dtorKind =
594 variable->getType().isDestructedType();
595 if (dtorKind == QualType::DK_none) continue;
596
597 CodeGenFunction::Destroyer *destroyer;
598
599 // Block captures count as local values and have imprecise semantics.
600 // They also can't be arrays, so need to worry about that.
601 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000602 destroyer = CodeGenFunction::destroyARCStrongImprecise;
John McCall08ef4662011-11-10 08:15:53 +0000603 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000604 destroyer = CGF.getDestroyer(dtorKind);
John McCall08ef4662011-11-10 08:15:53 +0000605 }
606
607 // GEP down to the address.
John McCall7f416cc2015-09-08 08:05:57 +0000608 Address addr = CGF.Builder.CreateStructGEP(blockInfo.LocalAddress,
609 capture.getIndex(),
610 capture.getOffset());
John McCall08ef4662011-11-10 08:15:53 +0000611
John McCallf4beacd2011-11-10 10:43:54 +0000612 // We can use that GEP as the dominating IP.
613 if (!blockInfo.DominatingIP)
John McCall7f416cc2015-09-08 08:05:57 +0000614 blockInfo.DominatingIP = cast<llvm::Instruction>(addr.getPointer());
John McCallf4beacd2011-11-10 10:43:54 +0000615
John McCall08ef4662011-11-10 08:15:53 +0000616 CleanupKind cleanupKind = InactiveNormalCleanup;
617 bool useArrayEHCleanup = CGF.needsEHCleanup(dtorKind);
618 if (useArrayEHCleanup)
619 cleanupKind = InactiveNormalAndEHCleanup;
620
621 CGF.pushDestroy(cleanupKind, addr, variable->getType(),
Peter Collingbourne1425b452012-01-26 03:33:36 +0000622 destroyer, useArrayEHCleanup);
John McCall08ef4662011-11-10 08:15:53 +0000623
624 // Remember where that cleanup was.
625 capture.setCleanup(CGF.EHStack.stable_begin());
626 }
627}
628
629/// Enter a full-expression with a non-trivial number of objects to
630/// clean up. This is in this file because, at the moment, the only
631/// kind of cleanup object is a BlockDecl*.
632void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups *E) {
633 assert(E->getNumObjects() != 0);
634 ArrayRef<ExprWithCleanups::CleanupObject> cleanups = E->getObjects();
635 for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
636 i = cleanups.begin(), e = cleanups.end(); i != e; ++i) {
637 enterBlockScope(*this, *i);
638 }
639}
640
641/// Find the layout for the given block in a linked list and remove it.
642static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
643 const BlockDecl *block) {
644 while (true) {
645 assert(head && *head);
646 CGBlockInfo *cur = *head;
647
648 // If this is the block we're looking for, splice it out of the list.
649 if (cur->getBlockDecl() == block) {
650 *head = cur->NextBlockInfo;
651 return cur;
652 }
653
654 head = &cur->NextBlockInfo;
655 }
656}
657
658/// Destroy a chain of block layouts.
659void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
660 assert(head && "destroying an empty chain");
661 do {
662 CGBlockInfo *cur = head;
663 head = cur->NextBlockInfo;
664 delete cur;
Craig Topper8a13c412014-05-21 05:09:00 +0000665 } while (head != nullptr);
John McCall08ef4662011-11-10 08:15:53 +0000666}
667
John McCall351762c2011-02-07 10:33:21 +0000668/// Emit a block literal expression in the current function.
669llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
John McCall08ef4662011-11-10 08:15:53 +0000670 // If the block has no captures, we won't have a pre-computed
671 // layout for it.
672 if (!blockExpr->getBlockDecl()->hasCaptures()) {
673 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
Richard Smithdafff942012-01-14 04:30:29 +0000674 computeBlockInfo(CGM, this, blockInfo);
John McCall08ef4662011-11-10 08:15:53 +0000675 blockInfo.BlockExpression = blockExpr;
676 return EmitBlockLiteral(blockInfo);
677 }
John McCall351762c2011-02-07 10:33:21 +0000678
John McCall08ef4662011-11-10 08:15:53 +0000679 // Find the block info for this block and take ownership of it.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000680 std::unique_ptr<CGBlockInfo> blockInfo;
John McCall08ef4662011-11-10 08:15:53 +0000681 blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
682 blockExpr->getBlockDecl()));
John McCall351762c2011-02-07 10:33:21 +0000683
John McCall08ef4662011-11-10 08:15:53 +0000684 blockInfo->BlockExpression = blockExpr;
685 return EmitBlockLiteral(*blockInfo);
686}
687
688llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
689 // Using the computed layout, generate the actual block function.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000690 bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
John McCall351762c2011-02-07 10:33:21 +0000691 llvm::Constant *blockFn
Fariborz Jahanian63628032012-06-26 16:06:38 +0000692 = CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
John McCalldec348f72013-05-03 07:33:41 +0000693 LocalDeclMap,
694 isLambdaConv);
John McCalle3dc1702011-02-15 09:22:45 +0000695 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000696
697 // If there is nothing to capture, we can emit this as a global block.
698 if (blockInfo.CanBeGlobal)
699 return buildGlobalBlock(CGM, blockInfo, blockFn);
700
701 // Otherwise, we have to emit this as a local block.
702
703 llvm::Constant *isa = CGM.getNSConcreteStackBlock();
John McCalle3dc1702011-02-15 09:22:45 +0000704 isa = llvm::ConstantExpr::getBitCast(isa, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000705
706 // Build the block descriptor.
707 llvm::Constant *descriptor = buildBlockDescriptor(CGM, blockInfo);
708
John McCall7f416cc2015-09-08 08:05:57 +0000709 Address blockAddr = blockInfo.LocalAddress;
710 assert(blockAddr.isValid() && "block has no address!");
John McCall351762c2011-02-07 10:33:21 +0000711
712 // Compute the initial on-stack block flags.
John McCallad7c5c12011-02-08 08:22:06 +0000713 BlockFlags flags = BLOCK_HAS_SIGNATURE;
Fariborz Jahanian23290b02012-11-01 18:32:55 +0000714 if (blockInfo.HasCapturedVariableLayout) flags |= BLOCK_HAS_EXTENDED_LAYOUT;
John McCall351762c2011-02-07 10:33:21 +0000715 if (blockInfo.NeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
716 if (blockInfo.HasCXXObject) flags |= BLOCK_HAS_CXX_OBJ;
John McCall85915252011-03-09 08:39:33 +0000717 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
John McCall351762c2011-02-07 10:33:21 +0000718
John McCall7f416cc2015-09-08 08:05:57 +0000719 auto projectField =
720 [&](unsigned index, CharUnits offset, const Twine &name) -> Address {
721 return Builder.CreateStructGEP(blockAddr, index, offset, name);
722 };
723 auto storeField =
724 [&](llvm::Value *value, unsigned index, CharUnits offset,
725 const Twine &name) {
726 Builder.CreateStore(value, projectField(index, offset, name));
727 };
728
729 // Initialize the block header.
730 {
731 // We assume all the header fields are densely packed.
732 unsigned index = 0;
733 CharUnits offset;
734 auto addHeaderField =
735 [&](llvm::Value *value, CharUnits size, const Twine &name) {
736 storeField(value, index, offset, name);
737 offset += size;
738 index++;
739 };
740
741 addHeaderField(isa, getPointerSize(), "block.isa");
742 addHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
743 getIntSize(), "block.flags");
744 addHeaderField(llvm::ConstantInt::get(IntTy, 0),
745 getIntSize(), "block.reserved");
746 addHeaderField(blockFn, getPointerSize(), "block.invoke");
747 addHeaderField(descriptor, getPointerSize(), "block.descriptor");
748 }
John McCall351762c2011-02-07 10:33:21 +0000749
750 // Finally, capture all the values into the block.
751 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
752
753 // First, 'this'.
754 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +0000755 Address addr = projectField(blockInfo.CXXThisIndex, blockInfo.CXXThisOffset,
756 "block.captured-this.addr");
John McCall351762c2011-02-07 10:33:21 +0000757 Builder.CreateStore(LoadCXXThis(), addr);
758 }
759
760 // Next, captured variables.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000761 for (const auto &CI : blockDecl->captures()) {
762 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +0000763 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
764
765 // Ignore constant captures.
766 if (capture.isConstant()) continue;
767
768 QualType type = variable->getType();
769
770 // This will be a [[type]]*, except that a byref entry will just be
771 // an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000772 Address blockField =
773 projectField(capture.getIndex(), capture.getOffset(), "block.captured");
John McCall351762c2011-02-07 10:33:21 +0000774
775 // Compute the address of the thing we're going to move into the
776 // block literal.
John McCall7f416cc2015-09-08 08:05:57 +0000777 Address src = Address::invalid();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000778 if (BlockInfo && CI.isNested()) {
John McCall351762c2011-02-07 10:33:21 +0000779 // We need to use the capture from the enclosing block.
780 const CGBlockInfo::Capture &enclosingCapture =
781 BlockInfo->getCapture(variable);
782
783 // This is a [[type]]*, except that a byref entry wil just be an i8**.
John McCall7f416cc2015-09-08 08:05:57 +0000784 src = Builder.CreateStructGEP(LoadBlockStruct(),
John McCall351762c2011-02-07 10:33:21 +0000785 enclosingCapture.getIndex(),
John McCall7f416cc2015-09-08 08:05:57 +0000786 enclosingCapture.getOffset(),
John McCall351762c2011-02-07 10:33:21 +0000787 "block.capture.addr");
Eli Friedman98b01ed2012-03-01 04:01:32 +0000788 } else if (blockDecl->isConversionFromLambda()) {
Eli Friedman2495ab02012-02-25 02:48:22 +0000789 // The lambda capture in a lambda's conversion-to-block-pointer is
Eli Friedman98b01ed2012-03-01 04:01:32 +0000790 // special; we'll simply emit it directly.
John McCall7f416cc2015-09-08 08:05:57 +0000791 src = Address::invalid();
John McCall351762c2011-02-07 10:33:21 +0000792 } else {
John McCalla37c2fa2013-03-04 06:32:36 +0000793 // Just look it up in the locals map, which will give us back a
794 // [[type]]*. If that doesn't work, do the more elaborate DRE
795 // emission.
John McCall7f416cc2015-09-08 08:05:57 +0000796 auto it = LocalDeclMap.find(variable);
797 if (it != LocalDeclMap.end()) {
798 src = it->second;
799 } else {
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000800 DeclRefExpr declRef(
801 const_cast<VarDecl *>(variable),
802 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(), type,
803 VK_LValue, SourceLocation());
John McCalla37c2fa2013-03-04 06:32:36 +0000804 src = EmitDeclRefLValue(&declRef).getAddress();
805 }
John McCall351762c2011-02-07 10:33:21 +0000806 }
807
808 // For byrefs, we just write the pointer to the byref struct into
809 // the block field. There's no need to chase the forwarding
810 // pointer at this point, since we're building something that will
811 // live a shorter life than the stack byref anyway.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000812 if (CI.isByRef()) {
John McCalle3dc1702011-02-15 09:22:45 +0000813 // Get a void* that points to the byref struct.
John McCall7f416cc2015-09-08 08:05:57 +0000814 llvm::Value *byrefPointer;
Aaron Ballman9371dd22014-03-14 18:34:04 +0000815 if (CI.isNested())
John McCall7f416cc2015-09-08 08:05:57 +0000816 byrefPointer = Builder.CreateLoad(src, "byref.capture");
John McCall351762c2011-02-07 10:33:21 +0000817 else
John McCall7f416cc2015-09-08 08:05:57 +0000818 byrefPointer = Builder.CreateBitCast(src.getPointer(), VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +0000819
John McCalle3dc1702011-02-15 09:22:45 +0000820 // Write that void* into the capture field.
John McCall7f416cc2015-09-08 08:05:57 +0000821 Builder.CreateStore(byrefPointer, blockField);
John McCall351762c2011-02-07 10:33:21 +0000822
823 // If we have a copy constructor, evaluate that into the block field.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000824 } else if (const Expr *copyExpr = CI.getCopyExpr()) {
Eli Friedman98b01ed2012-03-01 04:01:32 +0000825 if (blockDecl->isConversionFromLambda()) {
826 // If we have a lambda conversion, emit the expression
827 // directly into the block instead.
Eli Friedman98b01ed2012-03-01 04:01:32 +0000828 AggValueSlot Slot =
John McCall7f416cc2015-09-08 08:05:57 +0000829 AggValueSlot::forAddr(blockField, Qualifiers(),
Eli Friedman98b01ed2012-03-01 04:01:32 +0000830 AggValueSlot::IsDestructed,
831 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000832 AggValueSlot::IsNotAliased);
Eli Friedman98b01ed2012-03-01 04:01:32 +0000833 EmitAggExpr(copyExpr, Slot);
834 } else {
835 EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
836 }
John McCall351762c2011-02-07 10:33:21 +0000837
838 // If it's a reference variable, copy the reference into the block field.
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000839 } else if (type->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000840 llvm::Value *ref = Builder.CreateLoad(src, "ref.val");
841 Builder.CreateStore(ref, blockField);
John McCall4d14a902013-04-08 23:27:49 +0000842
843 // If this is an ARC __strong block-pointer variable, don't do a
844 // block copy.
845 //
846 // TODO: this can be generalized into the normal initialization logic:
847 // we should never need to do a block-copy when initializing a local
848 // variable, because the local variable's lifetime should be strictly
849 // contained within the stack block's.
850 } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
851 type->isBlockPointerType()) {
852 // Load the block and do a simple retain.
John McCall7f416cc2015-09-08 08:05:57 +0000853 llvm::Value *value = Builder.CreateLoad(src, "block.captured_block");
John McCall4d14a902013-04-08 23:27:49 +0000854 value = EmitARCRetainNonBlock(value);
855
856 // Do a primitive store to the block field.
John McCall7f416cc2015-09-08 08:05:57 +0000857 Builder.CreateStore(value, blockField);
John McCall351762c2011-02-07 10:33:21 +0000858
859 // Otherwise, fake up a POD copy into the block field.
860 } else {
John McCall31168b02011-06-15 23:02:42 +0000861 // Fake up a new variable so that EmitScalarInit doesn't think
862 // we're referring to the variable in its own initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000863 ImplicitParamDecl blockFieldPseudoVar(getContext(), /*DC*/ nullptr,
864 SourceLocation(), /*name*/ nullptr,
865 type);
John McCall31168b02011-06-15 23:02:42 +0000866
John McCall93be3f72011-02-07 18:37:40 +0000867 // We use one of these or the other depending on whether the
868 // reference is nested.
Alexey Bataev19acc3d2015-01-12 10:17:46 +0000869 DeclRefExpr declRef(const_cast<VarDecl *>(variable),
870 /*RefersToEnclosingVariableOrCapture*/ CI.isNested(),
871 type, VK_LValue, SourceLocation());
John McCall93be3f72011-02-07 18:37:40 +0000872
Fariborz Jahanian10317ea2011-11-02 22:53:43 +0000873 ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
John McCall113bee02012-03-10 09:33:50 +0000874 &declRef, VK_RValue);
David Blaikie7f138812014-12-09 22:04:13 +0000875 // FIXME: Pass a specific location for the expr init so that the store is
876 // attributed to a reasonable location - otherwise it may be attributed to
877 // locations of subexpressions in the initialization.
John McCall1553b192011-06-16 04:16:24 +0000878 EmitExprAsInit(&l2r, &blockFieldPseudoVar,
John McCall7f416cc2015-09-08 08:05:57 +0000879 MakeAddrLValue(blockField, type, AlignmentSource::Decl),
David Blaikie66e41972015-01-14 07:38:27 +0000880 /*captured by init*/ false);
John McCall351762c2011-02-07 10:33:21 +0000881 }
882
John McCall08ef4662011-11-10 08:15:53 +0000883 // Activate the cleanup if layout pushed one.
Aaron Ballman9371dd22014-03-14 18:34:04 +0000884 if (!CI.isByRef()) {
John McCall08ef4662011-11-10 08:15:53 +0000885 EHScopeStack::stable_iterator cleanup = capture.getCleanup();
886 if (cleanup.isValid())
John McCallf4beacd2011-11-10 10:43:54 +0000887 ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
John McCall31168b02011-06-15 23:02:42 +0000888 }
John McCall351762c2011-02-07 10:33:21 +0000889 }
890
891 // Cast to the converted block-pointer type, which happens (somewhat
892 // unfortunately) to be a pointer to function type.
893 llvm::Value *result =
John McCall7f416cc2015-09-08 08:05:57 +0000894 Builder.CreateBitCast(blockAddr.getPointer(),
John McCall351762c2011-02-07 10:33:21 +0000895 ConvertType(blockInfo.getBlockExpr()->getType()));
John McCall3882ace2011-01-05 12:14:39 +0000896
John McCall351762c2011-02-07 10:33:21 +0000897 return result;
Mike Stump85284ba2009-02-13 16:19:19 +0000898}
899
900
Chris Lattnera5f58b02011-07-09 17:41:47 +0000901llvm::Type *CodeGenModule::getBlockDescriptorType() {
Mike Stump650c9322009-02-13 15:16:56 +0000902 if (BlockDescriptorType)
903 return BlockDescriptorType;
904
Chris Lattnera5f58b02011-07-09 17:41:47 +0000905 llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000906 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000907
Mike Stump650c9322009-02-13 15:16:56 +0000908 // struct __block_descriptor {
909 // unsigned long reserved;
910 // unsigned long block_size;
Blaine Garstfc83aa02010-02-23 21:51:17 +0000911 //
912 // // later, the following will be added
913 //
914 // struct {
915 // void (*copyHelper)();
916 // void (*copyHelper)();
917 // } helpers; // !!! optional
918 //
919 // const char *signature; // the block signature
920 // const char *layout; // reserved
Mike Stump650c9322009-02-13 15:16:56 +0000921 // };
Chris Lattner845511f2011-06-18 22:49:11 +0000922 BlockDescriptorType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000923 llvm::StructType::create("struct.__block_descriptor",
Reid Kleckneree7cf842014-12-01 22:02:27 +0000924 UnsignedLongTy, UnsignedLongTy, nullptr);
Mike Stump650c9322009-02-13 15:16:56 +0000925
John McCall351762c2011-02-07 10:33:21 +0000926 // Now form a pointer to that.
927 BlockDescriptorType = llvm::PointerType::getUnqual(BlockDescriptorType);
Mike Stump650c9322009-02-13 15:16:56 +0000928 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000929}
930
Chris Lattnera5f58b02011-07-09 17:41:47 +0000931llvm::Type *CodeGenModule::getGenericBlockLiteralType() {
Mike Stump005c9a62009-02-13 15:25:34 +0000932 if (GenericBlockLiteralType)
933 return GenericBlockLiteralType;
934
Chris Lattnera5f58b02011-07-09 17:41:47 +0000935 llvm::Type *BlockDescPtrTy = getBlockDescriptorType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000936
Mike Stump005c9a62009-02-13 15:25:34 +0000937 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000938 // void *__isa;
939 // int __flags;
940 // int __reserved;
941 // void (*__invoke)(void *);
942 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000943 // };
Chris Lattnera5f58b02011-07-09 17:41:47 +0000944 GenericBlockLiteralType =
Chris Lattner5ec04a52011-08-12 17:43:31 +0000945 llvm::StructType::create("struct.__block_literal_generic",
946 VoidPtrTy, IntTy, IntTy, VoidPtrTy,
Reid Kleckneree7cf842014-12-01 22:02:27 +0000947 BlockDescPtrTy, nullptr);
Mike Stumpb7074c02009-02-13 15:32:32 +0000948
Mike Stump005c9a62009-02-13 15:25:34 +0000949 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000950}
951
Nick Lewycky2d84e842013-10-02 02:29:49 +0000952RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
Anders Carlssonbfb36712009-12-24 21:13:40 +0000953 ReturnValueSlot ReturnValue) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000954 const BlockPointerType *BPT =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000955 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpb7074c02009-02-13 15:32:32 +0000956
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000957 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
958
959 // Get a pointer to the generic block literal.
Chris Lattner2192fe52011-07-18 04:24:23 +0000960 llvm::Type *BlockLiteralTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000961 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000962
963 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000964 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000965 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
966
967 // Get the function pointer from the literal.
John McCall7f416cc2015-09-08 08:05:57 +0000968 llvm::Value *FuncPtr =
969 Builder.CreateStructGEP(CGM.getGenericBlockLiteralType(), BlockLiteral, 3);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000970
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000971 BlockLiteral = Builder.CreateBitCast(BlockLiteral, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000972
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000973 // Add the block literal.
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000974 CallArgList Args;
John McCall9dc0db22011-05-15 01:53:33 +0000975 Args.add(RValue::get(BlockLiteral), getContext().VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000976
Anders Carlsson479e6fc2009-04-08 23:13:16 +0000977 QualType FnType = BPT->getPointeeType();
978
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000979 // And the rest of the arguments.
David Blaikief05779e2015-07-21 18:37:18 +0000980 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), E->arguments());
Mike Stumpb7074c02009-02-13 15:32:32 +0000981
Anders Carlsson5f50c652009-04-07 22:10:22 +0000982 // Load the function.
John McCall7f416cc2015-09-08 08:05:57 +0000983 llvm::Value *Func = Builder.CreateAlignedLoad(FuncPtr, getPointerAlign());
Anders Carlsson5f50c652009-04-07 22:10:22 +0000984
John McCall85915252011-03-09 08:39:33 +0000985 const FunctionType *FuncTy = FnType->castAs<FunctionType>();
John McCalla729c622012-02-17 03:33:10 +0000986 const CGFunctionInfo &FnInfo =
John McCallc818bbb2012-12-07 07:03:17 +0000987 CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Anders Carlsson5f50c652009-04-07 22:10:22 +0000989 // Cast the function pointer to the right type.
John McCalla729c622012-02-17 03:33:10 +0000990 llvm::Type *BlockFTy = CGM.getTypes().GetFunctionType(FnInfo);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Chris Lattner2192fe52011-07-18 04:24:23 +0000992 llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson5f50c652009-04-07 22:10:22 +0000993 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000995 // And call the block.
Anders Carlssonbfb36712009-12-24 21:13:40 +0000996 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000997}
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000998
John McCall7f416cc2015-09-08 08:05:57 +0000999Address CodeGenFunction::GetAddrOfBlockDecl(const VarDecl *variable,
1000 bool isByRef) {
John McCall351762c2011-02-07 10:33:21 +00001001 assert(BlockInfo && "evaluating block ref without block information?");
1002 const CGBlockInfo::Capture &capture = BlockInfo->getCapture(variable);
John McCall87fe5d52010-05-20 01:18:31 +00001003
John McCall351762c2011-02-07 10:33:21 +00001004 // Handle constant captures.
John McCall7f416cc2015-09-08 08:05:57 +00001005 if (capture.isConstant()) return LocalDeclMap.find(variable)->second;
John McCall87fe5d52010-05-20 01:18:31 +00001006
John McCall7f416cc2015-09-08 08:05:57 +00001007 Address addr =
1008 Builder.CreateStructGEP(LoadBlockStruct(), capture.getIndex(),
1009 capture.getOffset(), "block.capture.addr");
John McCall87fe5d52010-05-20 01:18:31 +00001010
John McCall351762c2011-02-07 10:33:21 +00001011 if (isByRef) {
1012 // addr should be a void** right now. Load, then cast the result
1013 // to byref*.
Mike Stump97d01d52009-03-04 03:23:46 +00001014
John McCall7f416cc2015-09-08 08:05:57 +00001015 auto &byrefInfo = getBlockByrefInfo(variable);
1016 addr = Address(Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001017
John McCall7f416cc2015-09-08 08:05:57 +00001018 auto byrefPointerType = llvm::PointerType::get(byrefInfo.Type, 0);
1019 addr = Builder.CreateBitCast(addr, byrefPointerType, "byref.addr");
Mike Stump7fe9cc12009-10-21 03:49:08 +00001020
John McCall7f416cc2015-09-08 08:05:57 +00001021 addr = emitBlockByrefAddress(addr, byrefInfo, /*follow*/ true,
1022 variable->getName());
John McCall87fe5d52010-05-20 01:18:31 +00001023 }
1024
John McCall7f416cc2015-09-08 08:05:57 +00001025 if (auto refType = variable->getType()->getAs<ReferenceType>()) {
1026 addr = EmitLoadOfReference(addr, refType);
1027 }
Mike Stump7fe9cc12009-10-21 03:49:08 +00001028
John McCall351762c2011-02-07 10:33:21 +00001029 return addr;
Mike Stump97d01d52009-03-04 03:23:46 +00001030}
1031
Mike Stump2d5a2872009-02-14 22:16:35 +00001032llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001033CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
John McCalle3dc1702011-02-15 09:22:45 +00001034 const char *name) {
John McCall08ef4662011-11-10 08:15:53 +00001035 CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
1036 blockInfo.BlockExpression = blockExpr;
Mike Stumpb7074c02009-02-13 15:32:32 +00001037
John McCall351762c2011-02-07 10:33:21 +00001038 // Compute information about the layout, etc., of this block.
Craig Topper8a13c412014-05-21 05:09:00 +00001039 computeBlockInfo(*this, nullptr, blockInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001040
John McCall351762c2011-02-07 10:33:21 +00001041 // Using that metadata, generate the actual block function.
1042 llvm::Constant *blockFn;
1043 {
John McCall7f416cc2015-09-08 08:05:57 +00001044 CodeGenFunction::DeclMapTy LocalDeclMap;
John McCallad7c5c12011-02-08 08:22:06 +00001045 blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
1046 blockInfo,
John McCalldec348f72013-05-03 07:33:41 +00001047 LocalDeclMap,
Eli Friedman2495ab02012-02-25 02:48:22 +00001048 false);
John McCall351762c2011-02-07 10:33:21 +00001049 }
John McCalle3dc1702011-02-15 09:22:45 +00001050 blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
Mike Stumpb7074c02009-02-13 15:32:32 +00001051
John McCallad7c5c12011-02-08 08:22:06 +00001052 return buildGlobalBlock(*this, blockInfo, blockFn);
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001053}
1054
John McCall351762c2011-02-07 10:33:21 +00001055static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
1056 const CGBlockInfo &blockInfo,
1057 llvm::Constant *blockFn) {
1058 assert(blockInfo.CanBeGlobal);
1059
1060 // Generate the constants for the block literal initializer.
1061 llvm::Constant *fields[BlockHeaderSize];
1062
1063 // isa
1064 fields[0] = CGM.getNSConcreteGlobalBlock();
1065
1066 // __flags
John McCall85915252011-03-09 08:39:33 +00001067 BlockFlags flags = BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE;
1068 if (blockInfo.UsesStret) flags |= BLOCK_USE_STRET;
1069
John McCalle3dc1702011-02-15 09:22:45 +00001070 fields[1] = llvm::ConstantInt::get(CGM.IntTy, flags.getBitMask());
John McCall351762c2011-02-07 10:33:21 +00001071
1072 // Reserved
John McCalle3dc1702011-02-15 09:22:45 +00001073 fields[2] = llvm::Constant::getNullValue(CGM.IntTy);
John McCall351762c2011-02-07 10:33:21 +00001074
1075 // Function
1076 fields[3] = blockFn;
1077
1078 // Descriptor
1079 fields[4] = buildBlockDescriptor(CGM, blockInfo);
1080
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001081 llvm::Constant *init = llvm::ConstantStruct::getAnon(fields);
John McCall351762c2011-02-07 10:33:21 +00001082
1083 llvm::GlobalVariable *literal =
1084 new llvm::GlobalVariable(CGM.getModule(),
1085 init->getType(),
1086 /*constant*/ true,
1087 llvm::GlobalVariable::InternalLinkage,
1088 init,
1089 "__block_literal_global");
1090 literal->setAlignment(blockInfo.BlockAlign.getQuantity());
1091
1092 // Return a constant of the appropriately-casted type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001093 llvm::Type *requiredType =
John McCall351762c2011-02-07 10:33:21 +00001094 CGM.getTypes().ConvertType(blockInfo.getBlockExpr()->getType());
1095 return llvm::ConstantExpr::getBitCast(literal, requiredType);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +00001096}
1097
John McCall7f416cc2015-09-08 08:05:57 +00001098void CodeGenFunction::setBlockContextParameter(const ImplicitParamDecl *D,
1099 unsigned argNum,
1100 llvm::Value *arg) {
1101 assert(BlockInfo && "not emitting prologue of block invocation function?!");
1102
1103 llvm::Value *localAddr = nullptr;
1104 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1105 // Allocate a stack slot to let the debug info survive the RA.
1106 Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
1107 Builder.CreateStore(arg, alloc);
1108 localAddr = Builder.CreateLoad(alloc);
1109 }
1110
1111 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001112 if (CGM.getCodeGenOpts().getDebugInfo() >=
1113 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001114 DI->setLocation(D->getLocation());
1115 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, arg, argNum,
1116 localAddr, Builder);
1117 }
1118 }
1119
1120 SourceLocation StartLoc = BlockInfo->getBlockExpr()->getBody()->getLocStart();
1121 ApplyDebugLocation Scope(*this, StartLoc);
1122
1123 // Instead of messing around with LocalDeclMap, just set the value
1124 // directly as BlockPointer.
1125 BlockPointer = Builder.CreateBitCast(arg,
1126 BlockInfo->StructureType->getPointerTo(),
1127 "block");
1128}
1129
1130Address CodeGenFunction::LoadBlockStruct() {
1131 assert(BlockInfo && "not in a block invocation function!");
1132 assert(BlockPointer && "no block pointer set!");
1133 return Address(BlockPointer, BlockInfo->BlockAlign);
1134}
1135
Mike Stump4446dcf2009-03-05 08:32:30 +00001136llvm::Function *
John McCall351762c2011-02-07 10:33:21 +00001137CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
1138 const CGBlockInfo &blockInfo,
Eli Friedman2495ab02012-02-25 02:48:22 +00001139 const DeclMapTy &ldm,
1140 bool IsLambdaConversionToBlock) {
John McCall351762c2011-02-07 10:33:21 +00001141 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Devang Patel9074ed82009-04-15 21:51:44 +00001142
Fariborz Jahanian63628032012-06-26 16:06:38 +00001143 CurGD = GD;
David Blaikie1ae04912015-01-13 23:06:27 +00001144
1145 CurEHLocation = blockInfo.getBlockExpr()->getLocEnd();
Fariborz Jahanian63628032012-06-26 16:06:38 +00001146
John McCall351762c2011-02-07 10:33:21 +00001147 BlockInfo = &blockInfo;
Mike Stump11289f42009-09-09 15:08:12 +00001148
Mike Stump5469f292009-03-13 23:34:28 +00001149 // Arrange for local static and local extern declarations to appear
John McCall351762c2011-02-07 10:33:21 +00001150 // to be local to this function as well, in case they're directly
1151 // referenced in a block.
1152 for (DeclMapTy::const_iterator i = ldm.begin(), e = ldm.end(); i != e; ++i) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001153 const auto *var = dyn_cast<VarDecl>(i->first);
John McCall351762c2011-02-07 10:33:21 +00001154 if (var && !var->hasLocalStorage())
John McCall7f416cc2015-09-08 08:05:57 +00001155 setAddrOfLocalVar(var, i->second);
Mike Stump5469f292009-03-13 23:34:28 +00001156 }
1157
John McCall351762c2011-02-07 10:33:21 +00001158 // Begin building the function declaration.
Eli Friedman09a9b6e2009-03-28 03:24:54 +00001159
John McCall351762c2011-02-07 10:33:21 +00001160 // Build the argument list.
1161 FunctionArgList args;
Mike Stumpb7074c02009-02-13 15:32:32 +00001162
John McCall351762c2011-02-07 10:33:21 +00001163 // The first argument is the block pointer. Just take it as a void*
1164 // and cast it later.
1165 QualType selfTy = getContext().VoidPtrTy;
Mike Stump7fe9cc12009-10-21 03:49:08 +00001166 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpd0153282009-10-20 02:12:22 +00001167
Richard Smith053f6c62014-05-16 23:01:30 +00001168 ImplicitParamDecl selfDecl(getContext(), const_cast<BlockDecl*>(blockDecl),
John McCall147d0212011-02-22 22:38:33 +00001169 SourceLocation(), II, selfTy);
John McCalla738c252011-03-09 04:27:21 +00001170 args.push_back(&selfDecl);
Mike Stump7fe9cc12009-10-21 03:49:08 +00001171
John McCall351762c2011-02-07 10:33:21 +00001172 // Now add the rest of the parameters.
Benjamin Kramerf9890422015-02-17 16:48:30 +00001173 args.append(blockDecl->param_begin(), blockDecl->param_end());
John McCall87fe5d52010-05-20 01:18:31 +00001174
John McCall351762c2011-02-07 10:33:21 +00001175 // Create the function declaration.
John McCalla729c622012-02-17 03:33:10 +00001176 const FunctionProtoType *fnType = blockInfo.getBlockExpr()->getFunctionType();
Reid Kleckner4982b822014-01-31 22:54:50 +00001177 const CGFunctionInfo &fnInfo = CGM.getTypes().arrangeFreeFunctionDeclaration(
Alp Toker314cc812014-01-25 16:55:45 +00001178 fnType->getReturnType(), args, fnType->getExtInfo(),
1179 fnType->isVariadic());
Tim Northovere77cc392014-03-29 13:28:05 +00001180 if (CGM.ReturnSlotInterferesWithArgs(fnInfo))
John McCall85915252011-03-09 08:39:33 +00001181 blockInfo.UsesStret = true;
1182
John McCalla729c622012-02-17 03:33:10 +00001183 llvm::FunctionType *fnLLVMType = CGM.getTypes().GetFunctionType(fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001184
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001185 StringRef name = CGM.getBlockMangledName(GD, blockDecl);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001186 llvm::Function *fn = llvm::Function::Create(
1187 fnLLVMType, llvm::GlobalValue::InternalLinkage, name, &CGM.getModule());
John McCall351762c2011-02-07 10:33:21 +00001188 CGM.SetInternalFunctionAttributes(blockDecl, fn, fnInfo);
Mike Stumpb7074c02009-02-13 15:32:32 +00001189
John McCall351762c2011-02-07 10:33:21 +00001190 // Begin generating the function.
Alp Toker314cc812014-01-25 16:55:45 +00001191 StartFunction(blockDecl, fnType->getReturnType(), fn, fnInfo, args,
Adrian Prantl42d71b92014-04-10 23:21:53 +00001192 blockDecl->getLocation(),
Devang Patel5f070a52011-03-25 21:26:13 +00001193 blockInfo.getBlockExpr()->getBody()->getLocStart());
Mike Stumpb7074c02009-02-13 15:32:32 +00001194
John McCall147d0212011-02-22 22:38:33 +00001195 // Okay. Undo some of what StartFunction did.
John McCall7f416cc2015-09-08 08:05:57 +00001196
Adrian Prantl0f6df002013-03-29 19:20:35 +00001197 // At -O0 we generate an explicit alloca for the BlockPointer, so the RA
1198 // won't delete the dbg.declare intrinsics for captured variables.
1199 llvm::Value *BlockPointerDbgLoc = BlockPointer;
1200 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1201 // Allocate a stack slot for it, so we can point the debugger to it
John McCall7f416cc2015-09-08 08:05:57 +00001202 Address Alloca = CreateTempAlloca(BlockPointer->getType(),
1203 getPointerAlign(),
1204 "block.addr");
Adrian Prantl2832b4e2013-04-02 01:00:48 +00001205 // Set the DebugLocation to empty, so the store is recognized as a
1206 // frame setup instruction by llvm::DwarfDebug::beginFunction().
Adrian Prantl95b24e92015-02-03 20:00:54 +00001207 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001208 Builder.CreateStore(BlockPointer, Alloca);
1209 BlockPointerDbgLoc = Alloca.getPointer();
Adrian Prantl0f6df002013-03-29 19:20:35 +00001210 }
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001211
John McCall87fe5d52010-05-20 01:18:31 +00001212 // If we have a C++ 'this' reference, go ahead and force it into
1213 // existence now.
John McCall351762c2011-02-07 10:33:21 +00001214 if (blockDecl->capturesCXXThis()) {
John McCall7f416cc2015-09-08 08:05:57 +00001215 Address addr =
1216 Builder.CreateStructGEP(LoadBlockStruct(), blockInfo.CXXThisIndex,
1217 blockInfo.CXXThisOffset, "block.captured-this");
John McCall351762c2011-02-07 10:33:21 +00001218 CXXThisValue = Builder.CreateLoad(addr, "this");
John McCall87fe5d52010-05-20 01:18:31 +00001219 }
1220
John McCall351762c2011-02-07 10:33:21 +00001221 // Also force all the constant captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00001222 for (const auto &CI : blockDecl->captures()) {
1223 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001224 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1225 if (!capture.isConstant()) continue;
1226
John McCall7f416cc2015-09-08 08:05:57 +00001227 CharUnits align = getContext().getDeclAlign(variable);
1228 Address alloca =
1229 CreateMemTemp(variable->getType(), align, "block.captured-const");
John McCall351762c2011-02-07 10:33:21 +00001230
John McCall7f416cc2015-09-08 08:05:57 +00001231 Builder.CreateStore(capture.getConstant(), alloca);
John McCall351762c2011-02-07 10:33:21 +00001232
John McCall7f416cc2015-09-08 08:05:57 +00001233 setAddrOfLocalVar(variable, alloca);
John McCall9d42f0f2010-05-21 04:11:14 +00001234 }
1235
John McCall113bee02012-03-10 09:33:50 +00001236 // Save a spot to insert the debug information for all the DeclRefExprs.
Mike Stump017460a2009-10-01 22:29:41 +00001237 llvm::BasicBlock *entry = Builder.GetInsertBlock();
1238 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
1239 --entry_ptr;
1240
Eli Friedman2495ab02012-02-25 02:48:22 +00001241 if (IsLambdaConversionToBlock)
1242 EmitLambdaBlockInvokeBody();
Bob Wilsonc845c002014-03-06 20:24:27 +00001243 else {
Serge Pavlov3a561452015-12-06 14:32:39 +00001244 PGO.assignRegionCounters(GlobalDecl(blockDecl), fn);
Justin Bogner66242d62015-04-23 23:06:47 +00001245 incrementProfileCounter(blockDecl->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00001246 EmitStmt(blockDecl->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +00001247 }
Mike Stump017460a2009-10-01 22:29:41 +00001248
Mike Stump7d699112009-10-01 00:27:30 +00001249 // Remember where we were...
1250 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stump017460a2009-10-01 22:29:41 +00001251
Mike Stump7d699112009-10-01 00:27:30 +00001252 // Go back to the entry.
Mike Stump017460a2009-10-01 22:29:41 +00001253 ++entry_ptr;
1254 Builder.SetInsertPoint(entry, entry_ptr);
1255
John McCall113bee02012-03-10 09:33:50 +00001256 // Emit debug information for all the DeclRefExprs.
John McCall351762c2011-02-07 10:33:21 +00001257 // FIXME: also for 'this'
Mike Stump2e722b92009-09-30 02:43:10 +00001258 if (CGDebugInfo *DI = getDebugInfo()) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001259 for (const auto &CI : blockDecl->captures()) {
1260 const VarDecl *variable = CI.getVariable();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001261 DI->EmitLocation(Builder, variable->getLocation());
John McCall351762c2011-02-07 10:33:21 +00001262
Benjamin Kramer8c305922016-02-02 11:06:51 +00001263 if (CGM.getCodeGenOpts().getDebugInfo() >=
1264 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001265 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1266 if (capture.isConstant()) {
John McCall7f416cc2015-09-08 08:05:57 +00001267 auto addr = LocalDeclMap.find(variable)->second;
1268 DI->EmitDeclareOfAutoVariable(variable, addr.getPointer(),
Alexey Samsonov74a38682012-05-04 07:39:27 +00001269 Builder);
1270 continue;
1271 }
John McCall351762c2011-02-07 10:33:21 +00001272
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +00001273 DI->EmitDeclareOfBlockDeclRefVariable(
1274 variable, BlockPointerDbgLoc, Builder, blockInfo,
1275 entry_ptr == entry->end() ? nullptr : &*entry_ptr);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001276 }
Mike Stump2e722b92009-09-30 02:43:10 +00001277 }
Manman Renab08a9a2013-01-04 18:51:35 +00001278 // Recover location if it was changed in the above loop.
1279 DI->EmitLocation(Builder,
Adrian Prantl83e30fd2013-04-08 20:52:12 +00001280 cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Mike Stump2e722b92009-09-30 02:43:10 +00001281 }
John McCall351762c2011-02-07 10:33:21 +00001282
Mike Stump7d699112009-10-01 00:27:30 +00001283 // And resume where we left off.
Craig Topper8a13c412014-05-21 05:09:00 +00001284 if (resume == nullptr)
Mike Stump7d699112009-10-01 00:27:30 +00001285 Builder.ClearInsertionPoint();
1286 else
1287 Builder.SetInsertPoint(resume);
Mike Stump2e722b92009-09-30 02:43:10 +00001288
John McCall351762c2011-02-07 10:33:21 +00001289 FinishFunction(cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001290
John McCall351762c2011-02-07 10:33:21 +00001291 return fn;
Anders Carlsson6a60fa22009-02-12 17:55:02 +00001292}
Mike Stump1db7d042009-02-28 09:07:16 +00001293
John McCall351762c2011-02-07 10:33:21 +00001294/*
1295 notes.push_back(HelperInfo());
1296 HelperInfo &note = notes.back();
1297 note.index = capture.getIndex();
1298 note.RequiresCopying = (ci->hasCopyExpr() || BlockRequiresCopying(type));
1299 note.cxxbar_import = ci->getCopyExpr();
Mike Stump1db7d042009-02-28 09:07:16 +00001300
John McCall351762c2011-02-07 10:33:21 +00001301 if (ci->isByRef()) {
1302 note.flag = BLOCK_FIELD_IS_BYREF;
1303 if (type.isObjCGCWeak())
1304 note.flag |= BLOCK_FIELD_IS_WEAK;
1305 } else if (type->isBlockPointerType()) {
1306 note.flag = BLOCK_FIELD_IS_BLOCK;
1307 } else {
1308 note.flag = BLOCK_FIELD_IS_OBJECT;
1309 }
1310 */
Mike Stump1db7d042009-02-28 09:07:16 +00001311
John McCallf593b102013-01-22 03:56:22 +00001312/// Generate the copy-helper function for a block closure object:
1313/// static void block_copy_helper(block_t *dst, block_t *src);
1314/// The runtime will have previously initialized 'dst' by doing a
1315/// bit-copy of 'src'.
1316///
1317/// Note that this copies an entire block closure object to the heap;
1318/// it should not be confused with a 'byref copy helper', which moves
1319/// the contents of an individual __block variable to the heap.
John McCall351762c2011-02-07 10:33:21 +00001320llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001321CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001322 ASTContext &C = getContext();
1323
1324 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001325 ImplicitParamDecl dstDecl(getContext(), nullptr, SourceLocation(), nullptr,
1326 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001327 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00001328 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1329 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001330 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001331
Reid Kleckner4982b822014-01-31 22:54:50 +00001332 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1333 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001334
John McCall351762c2011-02-07 10:33:21 +00001335 // FIXME: it would be nice if these were mergeable with things with
1336 // identical semantics.
John McCalla729c622012-02-17 03:33:10 +00001337 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001338
1339 llvm::Function *Fn =
1340 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001341 "__copy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001342
1343 IdentifierInfo *II
1344 = &CGM.getContext().Idents.get("__copy_helper_block_");
1345
John McCall351762c2011-02-07 10:33:21 +00001346 FunctionDecl *FD = FunctionDecl::Create(C,
1347 C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001348 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001349 SourceLocation(), II, C.VoidTy,
1350 nullptr, SC_Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001351 false,
Eric Christopher56ef3742012-04-12 00:35:04 +00001352 false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001353
1354 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1355
Adrian Prantl95b24e92015-02-03 20:00:54 +00001356 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001357 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl39428e72015-02-03 18:40:42 +00001358 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001359 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Chris Lattner2192fe52011-07-18 04:24:23 +00001360 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001361
John McCall7f416cc2015-09-08 08:05:57 +00001362 Address src = GetAddrOfLocalVar(&srcDecl);
1363 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001364 src = Builder.CreateBitCast(src, structPtrTy, "block.source");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001365
John McCall7f416cc2015-09-08 08:05:57 +00001366 Address dst = GetAddrOfLocalVar(&dstDecl);
1367 dst = Address(Builder.CreateLoad(dst), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001368 dst = Builder.CreateBitCast(dst, structPtrTy, "block.dest");
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001369
John McCall351762c2011-02-07 10:33:21 +00001370 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001371
Aaron Ballman9371dd22014-03-14 18:34:04 +00001372 for (const auto &CI : blockDecl->captures()) {
1373 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001374 QualType type = variable->getType();
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001375
John McCall351762c2011-02-07 10:33:21 +00001376 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1377 if (capture.isConstant()) continue;
1378
Aaron Ballman9371dd22014-03-14 18:34:04 +00001379 const Expr *copyExpr = CI.getCopyExpr();
John McCall31168b02011-06-15 23:02:42 +00001380 BlockFieldFlags flags;
1381
John McCalle68b8f42012-10-17 02:28:37 +00001382 bool useARCWeakCopy = false;
1383 bool useARCStrongCopy = false;
John McCall351762c2011-02-07 10:33:21 +00001384
1385 if (copyExpr) {
Aaron Ballman9371dd22014-03-14 18:34:04 +00001386 assert(!CI.isByRef());
John McCall351762c2011-02-07 10:33:21 +00001387 // don't bother computing flags
John McCall31168b02011-06-15 23:02:42 +00001388
Aaron Ballman9371dd22014-03-14 18:34:04 +00001389 } else if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001390 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001391 if (type.isObjCGCWeak())
1392 flags |= BLOCK_FIELD_IS_WEAK;
John McCall351762c2011-02-07 10:33:21 +00001393
John McCall31168b02011-06-15 23:02:42 +00001394 } else if (type->isObjCRetainableType()) {
1395 flags = BLOCK_FIELD_IS_OBJECT;
John McCalle68b8f42012-10-17 02:28:37 +00001396 bool isBlockPointer = type->isBlockPointerType();
1397 if (isBlockPointer)
John McCall31168b02011-06-15 23:02:42 +00001398 flags = BLOCK_FIELD_IS_BLOCK;
1399
1400 // Special rules for ARC captures:
John McCall460ce582015-10-22 18:38:17 +00001401 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001402
John McCall460ce582015-10-22 18:38:17 +00001403 // We need to register __weak direct captures with the runtime.
1404 if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1405 useARCWeakCopy = true;
John McCall31168b02011-06-15 23:02:42 +00001406
John McCall460ce582015-10-22 18:38:17 +00001407 // We need to retain the copied value for __strong direct captures.
1408 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1409 // If it's a block pointer, we have to copy the block and
1410 // assign that to the destination pointer, so we might as
1411 // well use _Block_object_assign. Otherwise we can avoid that.
1412 if (!isBlockPointer)
1413 useARCStrongCopy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001414
1415 // Non-ARC captures of retainable pointers are strong and
1416 // therefore require a call to _Block_object_assign.
John McCall460ce582015-10-22 18:38:17 +00001417 } else if (!qs.getObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
John McCalle68b8f42012-10-17 02:28:37 +00001418 // fall through
John McCall460ce582015-10-22 18:38:17 +00001419
1420 // Otherwise the memcpy is fine.
1421 } else {
1422 continue;
John McCall31168b02011-06-15 23:02:42 +00001423 }
John McCall460ce582015-10-22 18:38:17 +00001424
1425 // For all other types, the memcpy is fine.
John McCall31168b02011-06-15 23:02:42 +00001426 } else {
1427 continue;
1428 }
John McCall351762c2011-02-07 10:33:21 +00001429
1430 unsigned index = capture.getIndex();
John McCall7f416cc2015-09-08 08:05:57 +00001431 Address srcField = Builder.CreateStructGEP(src, index, capture.getOffset());
1432 Address dstField = Builder.CreateStructGEP(dst, index, capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001433
1434 // If there's an explicit copy expression, we do that.
1435 if (copyExpr) {
John McCallad7c5c12011-02-08 08:22:06 +00001436 EmitSynthesizedCXXCopyCtor(dstField, srcField, copyExpr);
John McCalle68b8f42012-10-17 02:28:37 +00001437 } else if (useARCWeakCopy) {
John McCall31168b02011-06-15 23:02:42 +00001438 EmitARCCopyWeak(dstField, srcField);
John McCall351762c2011-02-07 10:33:21 +00001439 } else {
1440 llvm::Value *srcValue = Builder.CreateLoad(srcField, "blockcopy.src");
John McCalle68b8f42012-10-17 02:28:37 +00001441 if (useARCStrongCopy) {
1442 // At -O0, store null into the destination field (so that the
1443 // storeStrong doesn't over-release) and then call storeStrong.
1444 // This is a workaround to not having an initStrong call.
1445 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001446 auto *ty = cast<llvm::PointerType>(srcValue->getType());
John McCalle68b8f42012-10-17 02:28:37 +00001447 llvm::Value *null = llvm::ConstantPointerNull::get(ty);
1448 Builder.CreateStore(null, dstField);
1449 EmitARCStoreStrongCall(dstField, srcValue, true);
1450
1451 // With optimization enabled, take advantage of the fact that
1452 // the blocks runtime guarantees a memcpy of the block data, and
1453 // just emit a retain of the src field.
1454 } else {
1455 EmitARCRetainNonBlock(srcValue);
1456
1457 // We don't need this anymore, so kill it. It's not quite
1458 // worth the annoyance to avoid creating it in the first place.
John McCall7f416cc2015-09-08 08:05:57 +00001459 cast<llvm::Instruction>(dstField.getPointer())->eraseFromParent();
John McCalle68b8f42012-10-17 02:28:37 +00001460 }
1461 } else {
1462 srcValue = Builder.CreateBitCast(srcValue, VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001463 llvm::Value *dstAddr =
1464 Builder.CreateBitCast(dstField.getPointer(), VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00001465 llvm::Value *args[] = {
1466 dstAddr, srcValue, llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
1467 };
1468
1469 bool copyCanThrow = false;
Aaron Ballman9371dd22014-03-14 18:34:04 +00001470 if (CI.isByRef() && variable->getType()->getAsCXXRecordDecl()) {
John McCall882987f2013-02-28 19:01:20 +00001471 const Expr *copyExpr =
1472 CGM.getContext().getBlockVarCopyInits(variable);
1473 if (copyExpr) {
1474 copyCanThrow = true; // FIXME: reuse the noexcept logic
1475 }
1476 }
1477
1478 if (copyCanThrow) {
1479 EmitRuntimeCallOrInvoke(CGM.getBlockObjectAssign(), args);
1480 } else {
1481 EmitNounwindRuntimeCall(CGM.getBlockObjectAssign(), args);
1482 }
John McCalle68b8f42012-10-17 02:28:37 +00001483 }
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001484 }
1485 }
1486
John McCallad7c5c12011-02-08 08:22:06 +00001487 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001488
John McCalle3dc1702011-02-15 09:22:45 +00001489 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +00001490}
1491
John McCallf593b102013-01-22 03:56:22 +00001492/// Generate the destroy-helper function for a block closure object:
1493/// static void block_destroy_helper(block_t *theBlock);
1494///
1495/// Note that this destroys a heap-allocated block closure object;
1496/// it should not be confused with a 'byref destroy helper', which
1497/// destroys the heap-allocated contents of an individual __block
1498/// variable.
John McCall351762c2011-02-07 10:33:21 +00001499llvm::Constant *
John McCallad7c5c12011-02-08 08:22:06 +00001500CodeGenFunction::GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo) {
John McCall351762c2011-02-07 10:33:21 +00001501 ASTContext &C = getContext();
Mike Stump0c743272009-03-06 01:33:24 +00001502
John McCall351762c2011-02-07 10:33:21 +00001503 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001504 ImplicitParamDecl srcDecl(getContext(), nullptr, SourceLocation(), nullptr,
1505 C.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001506 args.push_back(&srcDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Reid Kleckner4982b822014-01-31 22:54:50 +00001508 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
1509 C.VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stump0c743272009-03-06 01:33:24 +00001510
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001511 // FIXME: We'd like to put these into a mergable by content, with
1512 // internal linkage.
John McCalla729c622012-02-17 03:33:10 +00001513 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Mike Stump0c743272009-03-06 01:33:24 +00001514
1515 llvm::Function *Fn =
1516 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramerd6b28fc2010-01-22 13:59:13 +00001517 "__destroy_helper_block_", &CGM.getModule());
Mike Stump0c743272009-03-06 01:33:24 +00001518
1519 IdentifierInfo *II
1520 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1521
John McCall351762c2011-02-07 10:33:21 +00001522 FunctionDecl *FD = FunctionDecl::Create(C, C.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001523 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001524 SourceLocation(), II, C.VoidTy,
1525 nullptr, SC_Static,
Eric Christopher56ef3742012-04-12 00:35:04 +00001526 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001527
1528 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1529
Adrian Prantl49a78562013-07-24 20:34:39 +00001530 // Create a scope with an artificial location for the body of this function.
Adrian Prantl95b24e92015-02-03 20:00:54 +00001531 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Adrian Prantl22e66b42014-04-11 01:13:04 +00001532 StartFunction(FD, C.VoidTy, Fn, FI, args);
Adrian Prantl95b24e92015-02-03 20:00:54 +00001533 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Mike Stump6f7d9f82009-03-07 02:53:18 +00001534
Chris Lattner2192fe52011-07-18 04:24:23 +00001535 llvm::Type *structPtrTy = blockInfo.StructureType->getPointerTo();
Mike Stump6f7d9f82009-03-07 02:53:18 +00001536
John McCall7f416cc2015-09-08 08:05:57 +00001537 Address src = GetAddrOfLocalVar(&srcDecl);
1538 src = Address(Builder.CreateLoad(src), blockInfo.BlockAlign);
John McCallad7c5c12011-02-08 08:22:06 +00001539 src = Builder.CreateBitCast(src, structPtrTy, "block");
Mike Stump6f7d9f82009-03-07 02:53:18 +00001540
John McCall351762c2011-02-07 10:33:21 +00001541 const BlockDecl *blockDecl = blockInfo.getBlockDecl();
1542
John McCallad7c5c12011-02-08 08:22:06 +00001543 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall351762c2011-02-07 10:33:21 +00001544
Aaron Ballman9371dd22014-03-14 18:34:04 +00001545 for (const auto &CI : blockDecl->captures()) {
1546 const VarDecl *variable = CI.getVariable();
John McCall351762c2011-02-07 10:33:21 +00001547 QualType type = variable->getType();
1548
1549 const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
1550 if (capture.isConstant()) continue;
1551
John McCallad7c5c12011-02-08 08:22:06 +00001552 BlockFieldFlags flags;
Craig Topper8a13c412014-05-21 05:09:00 +00001553 const CXXDestructorDecl *dtor = nullptr;
John McCall351762c2011-02-07 10:33:21 +00001554
John McCalle68b8f42012-10-17 02:28:37 +00001555 bool useARCWeakDestroy = false;
1556 bool useARCStrongDestroy = false;
John McCall31168b02011-06-15 23:02:42 +00001557
Aaron Ballman9371dd22014-03-14 18:34:04 +00001558 if (CI.isByRef()) {
John McCall351762c2011-02-07 10:33:21 +00001559 flags = BLOCK_FIELD_IS_BYREF;
John McCall31168b02011-06-15 23:02:42 +00001560 if (type.isObjCGCWeak())
1561 flags |= BLOCK_FIELD_IS_WEAK;
1562 } else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1563 if (record->hasTrivialDestructor())
1564 continue;
1565 dtor = record->getDestructor();
1566 } else if (type->isObjCRetainableType()) {
John McCall351762c2011-02-07 10:33:21 +00001567 flags = BLOCK_FIELD_IS_OBJECT;
John McCall31168b02011-06-15 23:02:42 +00001568 if (type->isBlockPointerType())
1569 flags = BLOCK_FIELD_IS_BLOCK;
John McCall351762c2011-02-07 10:33:21 +00001570
John McCall31168b02011-06-15 23:02:42 +00001571 // Special rules for ARC captures.
John McCall460ce582015-10-22 18:38:17 +00001572 Qualifiers qs = type.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001573
John McCall460ce582015-10-22 18:38:17 +00001574 // Use objc_storeStrong for __strong direct captures; the
1575 // dynamic tools really like it when we do this.
1576 if (qs.getObjCLifetime() == Qualifiers::OCL_Strong) {
1577 useARCStrongDestroy = true;
John McCall31168b02011-06-15 23:02:42 +00001578
John McCall460ce582015-10-22 18:38:17 +00001579 // Support __weak direct captures.
1580 } else if (qs.getObjCLifetime() == Qualifiers::OCL_Weak) {
1581 useARCWeakDestroy = true;
John McCalle68b8f42012-10-17 02:28:37 +00001582
John McCall460ce582015-10-22 18:38:17 +00001583 // Non-ARC captures are strong, and we need to use _Block_object_dispose.
1584 } else if (!qs.hasObjCLifetime() && !getLangOpts().ObjCAutoRefCount) {
1585 // fall through
1586
1587 // Otherwise, we have nothing to do.
1588 } else {
1589 continue;
John McCall31168b02011-06-15 23:02:42 +00001590 }
1591 } else {
1592 continue;
1593 }
John McCall351762c2011-02-07 10:33:21 +00001594
John McCall7f416cc2015-09-08 08:05:57 +00001595 Address srcField =
1596 Builder.CreateStructGEP(src, capture.getIndex(), capture.getOffset());
John McCall351762c2011-02-07 10:33:21 +00001597
1598 // If there's an explicit copy expression, we do that.
1599 if (dtor) {
John McCallad7c5c12011-02-08 08:22:06 +00001600 PushDestructorCleanup(dtor, srcField);
John McCall351762c2011-02-07 10:33:21 +00001601
John McCall31168b02011-06-15 23:02:42 +00001602 // If this is a __weak capture, emit the release directly.
John McCalle68b8f42012-10-17 02:28:37 +00001603 } else if (useARCWeakDestroy) {
John McCall31168b02011-06-15 23:02:42 +00001604 EmitARCDestroyWeak(srcField);
1605
John McCalle68b8f42012-10-17 02:28:37 +00001606 // Destroy strong objects with a call if requested.
1607 } else if (useARCStrongDestroy) {
John McCallcdda29c2013-03-13 03:10:54 +00001608 EmitARCDestroyStrong(srcField, ARCImpreciseLifetime);
John McCalle68b8f42012-10-17 02:28:37 +00001609
John McCall351762c2011-02-07 10:33:21 +00001610 // Otherwise we call _Block_object_dispose. It wouldn't be too
1611 // hard to just emit this as a cleanup if we wanted to make sure
1612 // that things were done in reverse.
1613 } else {
1614 llvm::Value *value = Builder.CreateLoad(srcField);
John McCalle3dc1702011-02-15 09:22:45 +00001615 value = Builder.CreateBitCast(value, VoidPtrTy);
John McCall351762c2011-02-07 10:33:21 +00001616 BuildBlockRelease(value, flags);
1617 }
Mike Stump6f7d9f82009-03-07 02:53:18 +00001618 }
1619
John McCall351762c2011-02-07 10:33:21 +00001620 cleanups.ForceCleanup();
1621
John McCallad7c5c12011-02-08 08:22:06 +00001622 FinishFunction();
Mike Stump0c743272009-03-06 01:33:24 +00001623
John McCalle3dc1702011-02-15 09:22:45 +00001624 return llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Mike Stump0c743272009-03-06 01:33:24 +00001625}
1626
John McCallf9b056b2011-03-31 08:03:29 +00001627namespace {
1628
1629/// Emits the copy/dispose helper functions for a __block object of id type.
John McCall7f416cc2015-09-08 08:05:57 +00001630class ObjectByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001631 BlockFieldFlags Flags;
1632
1633public:
1634 ObjectByrefHelpers(CharUnits alignment, BlockFieldFlags flags)
John McCall7f416cc2015-09-08 08:05:57 +00001635 : BlockByrefHelpers(alignment), Flags(flags) {}
John McCallf9b056b2011-03-31 08:03:29 +00001636
John McCall7f416cc2015-09-08 08:05:57 +00001637 void emitCopy(CodeGenFunction &CGF, Address destField,
1638 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001639 destField = CGF.Builder.CreateBitCast(destField, CGF.VoidPtrTy);
1640
1641 srcField = CGF.Builder.CreateBitCast(srcField, CGF.VoidPtrPtrTy);
1642 llvm::Value *srcValue = CGF.Builder.CreateLoad(srcField);
1643
1644 unsigned flags = (Flags | BLOCK_BYREF_CALLER).getBitMask();
1645
1646 llvm::Value *flagsVal = llvm::ConstantInt::get(CGF.Int32Ty, flags);
1647 llvm::Value *fn = CGF.CGM.getBlockObjectAssign();
John McCall882987f2013-02-28 19:01:20 +00001648
John McCall7f416cc2015-09-08 08:05:57 +00001649 llvm::Value *args[] = { destField.getPointer(), srcValue, flagsVal };
John McCall882987f2013-02-28 19:01:20 +00001650 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf9b056b2011-03-31 08:03:29 +00001651 }
1652
John McCall7f416cc2015-09-08 08:05:57 +00001653 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001654 field = CGF.Builder.CreateBitCast(field, CGF.Int8PtrTy->getPointerTo(0));
1655 llvm::Value *value = CGF.Builder.CreateLoad(field);
1656
1657 CGF.BuildBlockRelease(value, Flags | BLOCK_BYREF_CALLER);
1658 }
1659
Craig Topper4f12f102014-03-12 06:41:41 +00001660 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001661 id.AddInteger(Flags.getBitMask());
1662 }
1663};
1664
John McCall31168b02011-06-15 23:02:42 +00001665/// Emits the copy/dispose helpers for an ARC __block __weak variable.
John McCall7f416cc2015-09-08 08:05:57 +00001666class ARCWeakByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001667public:
John McCall7f416cc2015-09-08 08:05:57 +00001668 ARCWeakByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001669
John McCall7f416cc2015-09-08 08:05:57 +00001670 void emitCopy(CodeGenFunction &CGF, Address destField,
1671 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001672 CGF.EmitARCMoveWeak(destField, srcField);
1673 }
1674
John McCall7f416cc2015-09-08 08:05:57 +00001675 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCall31168b02011-06-15 23:02:42 +00001676 CGF.EmitARCDestroyWeak(field);
1677 }
1678
Craig Topper4f12f102014-03-12 06:41:41 +00001679 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001680 // 0 is distinguishable from all pointers and byref flags
1681 id.AddInteger(0);
1682 }
1683};
1684
1685/// Emits the copy/dispose helpers for an ARC __block __strong variable
1686/// that's not of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001687class ARCStrongByrefHelpers final : public BlockByrefHelpers {
John McCall31168b02011-06-15 23:02:42 +00001688public:
John McCall7f416cc2015-09-08 08:05:57 +00001689 ARCStrongByrefHelpers(CharUnits alignment) : BlockByrefHelpers(alignment) {}
John McCall31168b02011-06-15 23:02:42 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 void emitCopy(CodeGenFunction &CGF, Address destField,
1692 Address srcField) override {
John McCall31168b02011-06-15 23:02:42 +00001693 // Do a "move" by copying the value and then zeroing out the old
1694 // variable.
1695
John McCall7f416cc2015-09-08 08:05:57 +00001696 llvm::Value *value = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001697
John McCall31168b02011-06-15 23:02:42 +00001698 llvm::Value *null =
1699 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getType()));
John McCall3a237aa2011-11-09 03:17:26 +00001700
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001701 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00001702 CGF.Builder.CreateStore(null, destField);
Fariborz Jahaniana82e9262013-01-04 23:32:24 +00001703 CGF.EmitARCStoreStrongCall(destField, value, /*ignored*/ true);
1704 CGF.EmitARCStoreStrongCall(srcField, null, /*ignored*/ true);
1705 return;
1706 }
John McCall7f416cc2015-09-08 08:05:57 +00001707 CGF.Builder.CreateStore(value, destField);
1708 CGF.Builder.CreateStore(null, srcField);
John McCall31168b02011-06-15 23:02:42 +00001709 }
1710
John McCall7f416cc2015-09-08 08:05:57 +00001711 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001712 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001713 }
1714
Craig Topper4f12f102014-03-12 06:41:41 +00001715 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall31168b02011-06-15 23:02:42 +00001716 // 1 is distinguishable from all pointers and byref flags
1717 id.AddInteger(1);
1718 }
1719};
1720
John McCall3a237aa2011-11-09 03:17:26 +00001721/// Emits the copy/dispose helpers for an ARC __block __strong
1722/// variable that's of block-pointer type.
John McCall7f416cc2015-09-08 08:05:57 +00001723class ARCStrongBlockByrefHelpers final : public BlockByrefHelpers {
John McCall3a237aa2011-11-09 03:17:26 +00001724public:
John McCall7f416cc2015-09-08 08:05:57 +00001725 ARCStrongBlockByrefHelpers(CharUnits alignment)
1726 : BlockByrefHelpers(alignment) {}
John McCall3a237aa2011-11-09 03:17:26 +00001727
John McCall7f416cc2015-09-08 08:05:57 +00001728 void emitCopy(CodeGenFunction &CGF, Address destField,
1729 Address srcField) override {
John McCall3a237aa2011-11-09 03:17:26 +00001730 // Do the copy with objc_retainBlock; that's all that
1731 // _Block_object_assign would do anyway, and we'd have to pass the
1732 // right arguments to make sure it doesn't get no-op'ed.
John McCall7f416cc2015-09-08 08:05:57 +00001733 llvm::Value *oldValue = CGF.Builder.CreateLoad(srcField);
John McCall3a237aa2011-11-09 03:17:26 +00001734 llvm::Value *copy = CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ true);
John McCall7f416cc2015-09-08 08:05:57 +00001735 CGF.Builder.CreateStore(copy, destField);
John McCall3a237aa2011-11-09 03:17:26 +00001736 }
1737
John McCall7f416cc2015-09-08 08:05:57 +00001738 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallcdda29c2013-03-13 03:10:54 +00001739 CGF.EmitARCDestroyStrong(field, ARCImpreciseLifetime);
John McCall3a237aa2011-11-09 03:17:26 +00001740 }
1741
Craig Topper4f12f102014-03-12 06:41:41 +00001742 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCall3a237aa2011-11-09 03:17:26 +00001743 // 2 is distinguishable from all pointers and byref flags
1744 id.AddInteger(2);
1745 }
1746};
1747
John McCallf9b056b2011-03-31 08:03:29 +00001748/// Emits the copy/dispose helpers for a __block variable with a
1749/// nontrivial copy constructor or destructor.
John McCall7f416cc2015-09-08 08:05:57 +00001750class CXXByrefHelpers final : public BlockByrefHelpers {
John McCallf9b056b2011-03-31 08:03:29 +00001751 QualType VarType;
1752 const Expr *CopyExpr;
1753
1754public:
1755 CXXByrefHelpers(CharUnits alignment, QualType type,
1756 const Expr *copyExpr)
John McCall7f416cc2015-09-08 08:05:57 +00001757 : BlockByrefHelpers(alignment), VarType(type), CopyExpr(copyExpr) {}
John McCallf9b056b2011-03-31 08:03:29 +00001758
Craig Topper8a13c412014-05-21 05:09:00 +00001759 bool needsCopy() const override { return CopyExpr != nullptr; }
John McCall7f416cc2015-09-08 08:05:57 +00001760 void emitCopy(CodeGenFunction &CGF, Address destField,
1761 Address srcField) override {
John McCallf9b056b2011-03-31 08:03:29 +00001762 if (!CopyExpr) return;
1763 CGF.EmitSynthesizedCXXCopyCtor(destField, srcField, CopyExpr);
1764 }
1765
John McCall7f416cc2015-09-08 08:05:57 +00001766 void emitDispose(CodeGenFunction &CGF, Address field) override {
John McCallf9b056b2011-03-31 08:03:29 +00001767 EHScopeStack::stable_iterator cleanupDepth = CGF.EHStack.stable_begin();
1768 CGF.PushDestructorCleanup(VarType, field);
1769 CGF.PopCleanupBlocks(cleanupDepth);
1770 }
1771
Craig Topper4f12f102014-03-12 06:41:41 +00001772 void profileImpl(llvm::FoldingSetNodeID &id) const override {
John McCallf9b056b2011-03-31 08:03:29 +00001773 id.AddPointer(VarType.getCanonicalType().getAsOpaquePtr());
1774 }
1775};
1776} // end anonymous namespace
1777
1778static llvm::Constant *
John McCall7f416cc2015-09-08 08:05:57 +00001779generateByrefCopyHelper(CodeGenFunction &CGF, const BlockByrefInfo &byrefInfo,
1780 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001781 ASTContext &Context = CGF.getContext();
1782
1783 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001784
John McCalla738c252011-03-09 04:27:21 +00001785 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001786 ImplicitParamDecl dst(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001787 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001788 args.push_back(&dst);
Mike Stumpf89230d2009-03-06 06:12:24 +00001789
Craig Topper8a13c412014-05-21 05:09:00 +00001790 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001791 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001792 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001793
Reid Kleckner4982b822014-01-31 22:54:50 +00001794 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1795 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001796
John McCall7f416cc2015-09-08 08:05:57 +00001797 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001798
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001799 // FIXME: We'd like to put these into a mergable by content, with
1800 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001801 llvm::Function *Fn =
1802 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
John McCallf9b056b2011-03-31 08:03:29 +00001803 "__Block_byref_object_copy_", &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001804
1805 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001806 = &Context.Idents.get("__Block_byref_object_copy_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001807
John McCallf9b056b2011-03-31 08:03:29 +00001808 FunctionDecl *FD = FunctionDecl::Create(Context,
1809 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001810 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001811 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001812 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001813 false, false);
John McCall31168b02011-06-15 23:02:42 +00001814
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001815 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1816
Adrian Prantl22e66b42014-04-11 01:13:04 +00001817 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpf89230d2009-03-06 06:12:24 +00001818
John McCall7f416cc2015-09-08 08:05:57 +00001819 if (generator.needsCopy()) {
1820 llvm::Type *byrefPtrType = byrefInfo.Type->getPointerTo(0);
Mike Stumpf89230d2009-03-06 06:12:24 +00001821
John McCallf9b056b2011-03-31 08:03:29 +00001822 // dst->x
John McCall7f416cc2015-09-08 08:05:57 +00001823 Address destField = CGF.GetAddrOfLocalVar(&dst);
1824 destField = Address(CGF.Builder.CreateLoad(destField),
1825 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001826 destField = CGF.Builder.CreateBitCast(destField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001827 destField = CGF.emitBlockByrefAddress(destField, byrefInfo, false,
1828 "dest-object");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001829
John McCallf9b056b2011-03-31 08:03:29 +00001830 // src->x
John McCall7f416cc2015-09-08 08:05:57 +00001831 Address srcField = CGF.GetAddrOfLocalVar(&src);
1832 srcField = Address(CGF.Builder.CreateLoad(srcField),
1833 byrefInfo.ByrefAlignment);
John McCallf9b056b2011-03-31 08:03:29 +00001834 srcField = CGF.Builder.CreateBitCast(srcField, byrefPtrType);
John McCall7f416cc2015-09-08 08:05:57 +00001835 srcField = CGF.emitBlockByrefAddress(srcField, byrefInfo, false,
1836 "src-object");
John McCallf9b056b2011-03-31 08:03:29 +00001837
John McCall7f416cc2015-09-08 08:05:57 +00001838 generator.emitCopy(CGF, destField, srcField);
John McCallf9b056b2011-03-31 08:03:29 +00001839 }
1840
1841 CGF.FinishFunction();
1842
1843 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001844}
1845
John McCallf9b056b2011-03-31 08:03:29 +00001846/// Build the copy helper for a __block variable.
1847static llvm::Constant *buildByrefCopyHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001848 const BlockByrefInfo &byrefInfo,
1849 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001850 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001851 return generateByrefCopyHelper(CGF, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001852}
1853
1854/// Generate code for a __block variable's dispose helper.
1855static llvm::Constant *
1856generateByrefDisposeHelper(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001857 const BlockByrefInfo &byrefInfo,
1858 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001859 ASTContext &Context = CGF.getContext();
1860 QualType R = Context.VoidTy;
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001861
John McCalla738c252011-03-09 04:27:21 +00001862 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00001863 ImplicitParamDecl src(CGF.getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +00001864 Context.VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +00001865 args.push_back(&src);
Mike Stump11289f42009-09-09 15:08:12 +00001866
Reid Kleckner4982b822014-01-31 22:54:50 +00001867 const CGFunctionInfo &FI = CGF.CGM.getTypes().arrangeFreeFunctionDeclaration(
1868 R, args, FunctionType::ExtInfo(), /*variadic=*/false);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001869
John McCall7f416cc2015-09-08 08:05:57 +00001870 llvm::FunctionType *LTy = CGF.CGM.getTypes().GetFunctionType(FI);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001871
Mike Stumpcbc2bca2009-06-05 23:26:36 +00001872 // FIXME: We'd like to put these into a mergable by content, with
1873 // internal linkage.
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001874 llvm::Function *Fn =
1875 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian50198092010-12-02 17:02:11 +00001876 "__Block_byref_object_dispose_",
John McCallf9b056b2011-03-31 08:03:29 +00001877 &CGF.CGM.getModule());
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001878
1879 IdentifierInfo *II
John McCallf9b056b2011-03-31 08:03:29 +00001880 = &Context.Idents.get("__Block_byref_object_dispose_");
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001881
John McCallf9b056b2011-03-31 08:03:29 +00001882 FunctionDecl *FD = FunctionDecl::Create(Context,
1883 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001884 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00001885 SourceLocation(), II, R, nullptr,
John McCall8e7d6562010-08-26 03:08:43 +00001886 SC_Static,
Eric Christopher0b1aef22012-04-12 02:16:49 +00001887 false, false);
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001888
1889 CGF.CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
1890
Adrian Prantl22e66b42014-04-11 01:13:04 +00001891 CGF.StartFunction(FD, R, Fn, FI, args);
Mike Stumpfbe25dd2009-03-06 04:53:30 +00001892
John McCall7f416cc2015-09-08 08:05:57 +00001893 if (generator.needsDispose()) {
1894 Address addr = CGF.GetAddrOfLocalVar(&src);
1895 addr = Address(CGF.Builder.CreateLoad(addr), byrefInfo.ByrefAlignment);
1896 auto byrefPtrType = byrefInfo.Type->getPointerTo(0);
1897 addr = CGF.Builder.CreateBitCast(addr, byrefPtrType);
1898 addr = CGF.emitBlockByrefAddress(addr, byrefInfo, false, "object");
John McCallad7c5c12011-02-08 08:22:06 +00001899
John McCall7f416cc2015-09-08 08:05:57 +00001900 generator.emitDispose(CGF, addr);
Fariborz Jahanian50198092010-12-02 17:02:11 +00001901 }
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001902
John McCallf9b056b2011-03-31 08:03:29 +00001903 CGF.FinishFunction();
John McCallad7c5c12011-02-08 08:22:06 +00001904
John McCallf9b056b2011-03-31 08:03:29 +00001905 return llvm::ConstantExpr::getBitCast(Fn, CGF.Int8PtrTy);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001906}
1907
John McCallf9b056b2011-03-31 08:03:29 +00001908/// Build the dispose helper for a __block variable.
1909static llvm::Constant *buildByrefDisposeHelper(CodeGenModule &CGM,
John McCall7f416cc2015-09-08 08:05:57 +00001910 const BlockByrefInfo &byrefInfo,
1911 BlockByrefHelpers &generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001912 CodeGenFunction CGF(CGM);
John McCall7f416cc2015-09-08 08:05:57 +00001913 return generateByrefDisposeHelper(CGF, byrefInfo, generator);
Mike Stumpee2a5ee2009-03-06 02:29:21 +00001914}
1915
John McCallf593b102013-01-22 03:56:22 +00001916/// Lazily build the copy and dispose helpers for a __block variable
1917/// with the given information.
David Blaikie92551612015-08-13 23:53:09 +00001918template <class T>
John McCall7f416cc2015-09-08 08:05:57 +00001919static T *buildByrefHelpers(CodeGenModule &CGM, const BlockByrefInfo &byrefInfo,
1920 T &&generator) {
John McCallf9b056b2011-03-31 08:03:29 +00001921 llvm::FoldingSetNodeID id;
John McCall7f416cc2015-09-08 08:05:57 +00001922 generator.Profile(id);
John McCallf9b056b2011-03-31 08:03:29 +00001923
1924 void *insertPos;
John McCall7f416cc2015-09-08 08:05:57 +00001925 BlockByrefHelpers *node
John McCallf9b056b2011-03-31 08:03:29 +00001926 = CGM.ByrefHelpersCache.FindNodeOrInsertPos(id, insertPos);
1927 if (node) return static_cast<T*>(node);
1928
John McCall7f416cc2015-09-08 08:05:57 +00001929 generator.CopyHelper = buildByrefCopyHelper(CGM, byrefInfo, generator);
1930 generator.DisposeHelper = buildByrefDisposeHelper(CGM, byrefInfo, generator);
John McCallf9b056b2011-03-31 08:03:29 +00001931
John McCall7f416cc2015-09-08 08:05:57 +00001932 T *copy = new (CGM.getContext()) T(std::move(generator));
John McCallf9b056b2011-03-31 08:03:29 +00001933 CGM.ByrefHelpersCache.InsertNode(copy, insertPos);
1934 return copy;
1935}
1936
John McCallf593b102013-01-22 03:56:22 +00001937/// Build the copy and dispose helpers for the given __block variable
1938/// emission. Places the helpers in the global cache. Returns null
1939/// if no helpers are required.
John McCall7f416cc2015-09-08 08:05:57 +00001940BlockByrefHelpers *
Chris Lattner2192fe52011-07-18 04:24:23 +00001941CodeGenFunction::buildByrefHelpers(llvm::StructType &byrefType,
John McCallf9b056b2011-03-31 08:03:29 +00001942 const AutoVarEmission &emission) {
1943 const VarDecl &var = *emission.Variable;
1944 QualType type = var.getType();
1945
John McCall7f416cc2015-09-08 08:05:57 +00001946 auto &byrefInfo = getBlockByrefInfo(&var);
1947
1948 // The alignment we care about for the purposes of uniquing byref
1949 // helpers is the alignment of the actual byref value field.
1950 CharUnits valueAlignment =
1951 byrefInfo.ByrefAlignment.alignmentAtOffset(byrefInfo.FieldOffset);
John McCallf593b102013-01-22 03:56:22 +00001952
John McCallf9b056b2011-03-31 08:03:29 +00001953 if (const CXXRecordDecl *record = type->getAsCXXRecordDecl()) {
1954 const Expr *copyExpr = CGM.getContext().getBlockVarCopyInits(&var);
Craig Topper8a13c412014-05-21 05:09:00 +00001955 if (!copyExpr && record->hasTrivialDestructor()) return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00001956
David Blaikie92551612015-08-13 23:53:09 +00001957 return ::buildByrefHelpers(
John McCall7f416cc2015-09-08 08:05:57 +00001958 CGM, byrefInfo, CXXByrefHelpers(valueAlignment, type, copyExpr));
John McCallf9b056b2011-03-31 08:03:29 +00001959 }
1960
John McCall31168b02011-06-15 23:02:42 +00001961 // Otherwise, if we don't have a retainable type, there's nothing to do.
1962 // that the runtime does extra copies.
Craig Topper8a13c412014-05-21 05:09:00 +00001963 if (!type->isObjCRetainableType()) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001964
1965 Qualifiers qs = type.getQualifiers();
1966
1967 // If we have lifetime, that dominates.
1968 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00001969 switch (lifetime) {
1970 case Qualifiers::OCL_None: llvm_unreachable("impossible");
1971
1972 // These are just bits as far as the runtime is concerned.
1973 case Qualifiers::OCL_ExplicitNone:
1974 case Qualifiers::OCL_Autoreleasing:
Craig Topper8a13c412014-05-21 05:09:00 +00001975 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001976
1977 // Tell the runtime that this is ARC __weak, called by the
1978 // byref routines.
David Blaikie92551612015-08-13 23:53:09 +00001979 case Qualifiers::OCL_Weak:
John McCall7f416cc2015-09-08 08:05:57 +00001980 return ::buildByrefHelpers(CGM, byrefInfo,
1981 ARCWeakByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001982
1983 // ARC __strong __block variables need to be retained.
1984 case Qualifiers::OCL_Strong:
John McCall3a237aa2011-11-09 03:17:26 +00001985 // Block pointers need to be copied, and there's no direct
1986 // transfer possible.
John McCall31168b02011-06-15 23:02:42 +00001987 if (type->isBlockPointerType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001988 return ::buildByrefHelpers(CGM, byrefInfo,
1989 ARCStrongBlockByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001990
1991 // Otherwise, we transfer ownership of the retain from the stack
1992 // to the heap.
1993 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001994 return ::buildByrefHelpers(CGM, byrefInfo,
1995 ARCStrongByrefHelpers(valueAlignment));
John McCall31168b02011-06-15 23:02:42 +00001996 }
1997 }
1998 llvm_unreachable("fell out of lifetime switch!");
1999 }
2000
John McCallf9b056b2011-03-31 08:03:29 +00002001 BlockFieldFlags flags;
2002 if (type->isBlockPointerType()) {
2003 flags |= BLOCK_FIELD_IS_BLOCK;
2004 } else if (CGM.getContext().isObjCNSObjectType(type) ||
2005 type->isObjCObjectPointerType()) {
2006 flags |= BLOCK_FIELD_IS_OBJECT;
2007 } else {
Craig Topper8a13c412014-05-21 05:09:00 +00002008 return nullptr;
John McCallf9b056b2011-03-31 08:03:29 +00002009 }
2010
2011 if (type.isObjCGCWeak())
2012 flags |= BLOCK_FIELD_IS_WEAK;
2013
John McCall7f416cc2015-09-08 08:05:57 +00002014 return ::buildByrefHelpers(CGM, byrefInfo,
2015 ObjectByrefHelpers(valueAlignment, flags));
Mike Stumpee2a5ee2009-03-06 02:29:21 +00002016}
2017
John McCall7f416cc2015-09-08 08:05:57 +00002018Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2019 const VarDecl *var,
2020 bool followForward) {
2021 auto &info = getBlockByrefInfo(var);
2022 return emitBlockByrefAddress(baseAddr, info, followForward, var->getName());
John McCall73064872011-03-31 01:59:53 +00002023}
2024
John McCall7f416cc2015-09-08 08:05:57 +00002025Address CodeGenFunction::emitBlockByrefAddress(Address baseAddr,
2026 const BlockByrefInfo &info,
2027 bool followForward,
2028 const llvm::Twine &name) {
2029 // Chase the forwarding address if requested.
2030 if (followForward) {
2031 Address forwardingAddr =
2032 Builder.CreateStructGEP(baseAddr, 1, getPointerSize(), "forwarding");
2033 baseAddr = Address(Builder.CreateLoad(forwardingAddr), info.ByrefAlignment);
2034 }
2035
2036 return Builder.CreateStructGEP(baseAddr, info.FieldIndex,
2037 info.FieldOffset, name);
John McCall73064872011-03-31 01:59:53 +00002038}
2039
John McCall7f416cc2015-09-08 08:05:57 +00002040/// BuildByrefInfo - This routine changes a __block variable declared as T x
John McCall73064872011-03-31 01:59:53 +00002041/// into:
2042///
2043/// struct {
2044/// void *__isa;
2045/// void *__forwarding;
2046/// int32_t __flags;
2047/// int32_t __size;
2048/// void *__copy_helper; // only if needed
2049/// void *__destroy_helper; // only if needed
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002050/// void *__byref_variable_layout;// only if needed
John McCall73064872011-03-31 01:59:53 +00002051/// char padding[X]; // only if needed
2052/// T x;
2053/// } x
2054///
John McCall7f416cc2015-09-08 08:05:57 +00002055const BlockByrefInfo &CodeGenFunction::getBlockByrefInfo(const VarDecl *D) {
2056 auto it = BlockByrefInfos.find(D);
2057 if (it != BlockByrefInfos.end())
2058 return it->second;
John McCall73064872011-03-31 01:59:53 +00002059
John McCall7f416cc2015-09-08 08:05:57 +00002060 llvm::StructType *byrefType =
Chris Lattner5ec04a52011-08-12 17:43:31 +00002061 llvm::StructType::create(getLLVMContext(),
2062 "struct.__block_byref_" + D->getNameAsString());
John McCall73064872011-03-31 01:59:53 +00002063
John McCall7f416cc2015-09-08 08:05:57 +00002064 QualType Ty = D->getType();
2065
2066 CharUnits size;
2067 SmallVector<llvm::Type *, 8> types;
2068
John McCall73064872011-03-31 01:59:53 +00002069 // void *__isa;
John McCall9dc0db22011-05-15 01:53:33 +00002070 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002071 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002072
2073 // void *__forwarding;
John McCall7f416cc2015-09-08 08:05:57 +00002074 types.push_back(llvm::PointerType::getUnqual(byrefType));
2075 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002076
2077 // int32_t __flags;
John McCall9dc0db22011-05-15 01:53:33 +00002078 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002079 size += CharUnits::fromQuantity(4);
John McCall73064872011-03-31 01:59:53 +00002080
2081 // int32_t __size;
John McCall9dc0db22011-05-15 01:53:33 +00002082 types.push_back(Int32Ty);
John McCall7f416cc2015-09-08 08:05:57 +00002083 size += CharUnits::fromQuantity(4);
2084
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00002085 // Note that this must match *exactly* the logic in buildByrefHelpers.
John McCall7f416cc2015-09-08 08:05:57 +00002086 bool hasCopyAndDispose = getContext().BlockRequiresCopying(Ty, D);
2087 if (hasCopyAndDispose) {
John McCall73064872011-03-31 01:59:53 +00002088 /// void *__copy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002089 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002090 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002091
2092 /// void *__destroy_helper;
John McCall9dc0db22011-05-15 01:53:33 +00002093 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002094 size += getPointerSize();
John McCall73064872011-03-31 01:59:53 +00002095 }
John McCall7f416cc2015-09-08 08:05:57 +00002096
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002097 bool HasByrefExtendedLayout = false;
2098 Qualifiers::ObjCLifetime Lifetime;
2099 if (getContext().getByrefLifetime(Ty, Lifetime, HasByrefExtendedLayout) &&
John McCall7f416cc2015-09-08 08:05:57 +00002100 HasByrefExtendedLayout) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002101 /// void *__byref_variable_layout;
2102 types.push_back(Int8PtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00002103 size += CharUnits::fromQuantity(PointerSizeInBytes);
John McCall73064872011-03-31 01:59:53 +00002104 }
2105
2106 // T x;
John McCall7f416cc2015-09-08 08:05:57 +00002107 llvm::Type *varTy = ConvertTypeForMem(Ty);
2108
2109 bool packed = false;
2110 CharUnits varAlign = getContext().getDeclAlign(D);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002111 CharUnits varOffset = size.alignTo(varAlign);
John McCall7f416cc2015-09-08 08:05:57 +00002112
2113 // We may have to insert padding.
2114 if (varOffset != size) {
2115 llvm::Type *paddingTy =
2116 llvm::ArrayType::get(Int8Ty, (varOffset - size).getQuantity());
2117
2118 types.push_back(paddingTy);
2119 size = varOffset;
2120
2121 // Conversely, we might have to prevent LLVM from inserting padding.
2122 } else if (CGM.getDataLayout().getABITypeAlignment(varTy)
2123 > varAlign.getQuantity()) {
2124 packed = true;
2125 }
2126 types.push_back(varTy);
2127
2128 byrefType->setBody(types, packed);
2129
2130 BlockByrefInfo info;
2131 info.Type = byrefType;
2132 info.FieldIndex = types.size() - 1;
2133 info.FieldOffset = varOffset;
2134 info.ByrefAlignment = std::max(varAlign, getPointerAlign());
2135
2136 auto pair = BlockByrefInfos.insert({D, info});
2137 assert(pair.second && "info was inserted recursively?");
2138 return pair.first->second;
John McCall73064872011-03-31 01:59:53 +00002139}
2140
2141/// Initialize the structural components of a __block variable, i.e.
2142/// everything but the actual object.
2143void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
John McCallf9b056b2011-03-31 08:03:29 +00002144 // Find the address of the local.
John McCall7f416cc2015-09-08 08:05:57 +00002145 Address addr = emission.Addr;
John McCall73064872011-03-31 01:59:53 +00002146
John McCallf9b056b2011-03-31 08:03:29 +00002147 // That's an alloca of the byref structure type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002148 llvm::StructType *byrefType = cast<llvm::StructType>(
John McCall7f416cc2015-09-08 08:05:57 +00002149 cast<llvm::PointerType>(addr.getPointer()->getType())->getElementType());
2150
2151 unsigned nextHeaderIndex = 0;
2152 CharUnits nextHeaderOffset;
2153 auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
2154 const Twine &name) {
2155 auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex,
2156 nextHeaderOffset, name);
2157 Builder.CreateStore(value, fieldAddr);
2158
2159 nextHeaderIndex++;
2160 nextHeaderOffset += fieldSize;
2161 };
John McCallf9b056b2011-03-31 08:03:29 +00002162
2163 // Build the byref helpers if necessary. This is null if we don't need any.
John McCall7f416cc2015-09-08 08:05:57 +00002164 BlockByrefHelpers *helpers = buildByrefHelpers(*byrefType, emission);
John McCall73064872011-03-31 01:59:53 +00002165
2166 const VarDecl &D = *emission.Variable;
2167 QualType type = D.getType();
2168
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002169 bool HasByrefExtendedLayout;
2170 Qualifiers::ObjCLifetime ByrefLifetime;
2171 bool ByRefHasLifetime =
2172 getContext().getByrefLifetime(type, ByrefLifetime, HasByrefExtendedLayout);
John McCall7f416cc2015-09-08 08:05:57 +00002173
John McCallf9b056b2011-03-31 08:03:29 +00002174 llvm::Value *V;
John McCall73064872011-03-31 01:59:53 +00002175
2176 // Initialize the 'isa', which is just 0 or 1.
2177 int isa = 0;
John McCallf9b056b2011-03-31 08:03:29 +00002178 if (type.isObjCGCWeak())
John McCall73064872011-03-31 01:59:53 +00002179 isa = 1;
2180 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
John McCall7f416cc2015-09-08 08:05:57 +00002181 storeHeaderField(V, getPointerSize(), "byref.isa");
John McCall73064872011-03-31 01:59:53 +00002182
2183 // Store the address of the variable into its own forwarding pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002184 storeHeaderField(addr.getPointer(), getPointerSize(), "byref.forwarding");
John McCall73064872011-03-31 01:59:53 +00002185
2186 // Blocks ABI:
2187 // c) the flags field is set to either 0 if no helper functions are
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002188 // needed or BLOCK_BYREF_HAS_COPY_DISPOSE if they are,
John McCall73064872011-03-31 01:59:53 +00002189 BlockFlags flags;
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002190 if (helpers) flags |= BLOCK_BYREF_HAS_COPY_DISPOSE;
2191 if (ByRefHasLifetime) {
2192 if (HasByrefExtendedLayout) flags |= BLOCK_BYREF_LAYOUT_EXTENDED;
2193 else switch (ByrefLifetime) {
2194 case Qualifiers::OCL_Strong:
2195 flags |= BLOCK_BYREF_LAYOUT_STRONG;
2196 break;
2197 case Qualifiers::OCL_Weak:
2198 flags |= BLOCK_BYREF_LAYOUT_WEAK;
2199 break;
2200 case Qualifiers::OCL_ExplicitNone:
2201 flags |= BLOCK_BYREF_LAYOUT_UNRETAINED;
2202 break;
2203 case Qualifiers::OCL_None:
2204 if (!type->isObjCObjectPointerType() && !type->isBlockPointerType())
2205 flags |= BLOCK_BYREF_LAYOUT_NON_OBJECT;
2206 break;
2207 default:
2208 break;
2209 }
2210 if (CGM.getLangOpts().ObjCGCBitmapPrint) {
2211 printf("\n Inline flag for BYREF variable layout (%d):", flags.getBitMask());
2212 if (flags & BLOCK_BYREF_HAS_COPY_DISPOSE)
2213 printf(" BLOCK_BYREF_HAS_COPY_DISPOSE");
2214 if (flags & BLOCK_BYREF_LAYOUT_MASK) {
2215 BlockFlags ThisFlag(flags.getBitMask() & BLOCK_BYREF_LAYOUT_MASK);
2216 if (ThisFlag == BLOCK_BYREF_LAYOUT_EXTENDED)
2217 printf(" BLOCK_BYREF_LAYOUT_EXTENDED");
2218 if (ThisFlag == BLOCK_BYREF_LAYOUT_STRONG)
2219 printf(" BLOCK_BYREF_LAYOUT_STRONG");
2220 if (ThisFlag == BLOCK_BYREF_LAYOUT_WEAK)
2221 printf(" BLOCK_BYREF_LAYOUT_WEAK");
2222 if (ThisFlag == BLOCK_BYREF_LAYOUT_UNRETAINED)
2223 printf(" BLOCK_BYREF_LAYOUT_UNRETAINED");
2224 if (ThisFlag == BLOCK_BYREF_LAYOUT_NON_OBJECT)
2225 printf(" BLOCK_BYREF_LAYOUT_NON_OBJECT");
2226 }
2227 printf("\n");
2228 }
2229 }
John McCall7f416cc2015-09-08 08:05:57 +00002230 storeHeaderField(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
2231 getIntSize(), "byref.flags");
John McCall73064872011-03-31 01:59:53 +00002232
John McCallf9b056b2011-03-31 08:03:29 +00002233 CharUnits byrefSize = CGM.GetTargetTypeStoreSize(byrefType);
2234 V = llvm::ConstantInt::get(IntTy, byrefSize.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +00002235 storeHeaderField(V, getIntSize(), "byref.size");
John McCall73064872011-03-31 01:59:53 +00002236
John McCallf9b056b2011-03-31 08:03:29 +00002237 if (helpers) {
John McCall7f416cc2015-09-08 08:05:57 +00002238 storeHeaderField(helpers->CopyHelper, getPointerSize(),
2239 "byref.copyHelper");
2240 storeHeaderField(helpers->DisposeHelper, getPointerSize(),
2241 "byref.disposeHelper");
John McCall73064872011-03-31 01:59:53 +00002242 }
John McCall7f416cc2015-09-08 08:05:57 +00002243
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002244 if (ByRefHasLifetime && HasByrefExtendedLayout) {
John McCall7f416cc2015-09-08 08:05:57 +00002245 auto layoutInfo = CGM.getObjCRuntime().BuildByrefLayout(CGM, type);
2246 storeHeaderField(layoutInfo, getPointerSize(), "byref.layout");
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00002247 }
John McCall73064872011-03-31 01:59:53 +00002248}
2249
John McCallad7c5c12011-02-08 08:22:06 +00002250void CodeGenFunction::BuildBlockRelease(llvm::Value *V, BlockFieldFlags flags) {
Daniel Dunbar900546d2010-07-16 00:00:15 +00002251 llvm::Value *F = CGM.getBlockObjectDispose();
John McCall882987f2013-02-28 19:01:20 +00002252 llvm::Value *args[] = {
2253 Builder.CreateBitCast(V, Int8PtrTy),
2254 llvm::ConstantInt::get(Int32Ty, flags.getBitMask())
2255 };
2256 EmitNounwindRuntimeCall(F, args); // FIXME: throwing destructors?
Mike Stump626aecc2009-03-05 01:23:13 +00002257}
John McCall73064872011-03-31 01:59:53 +00002258
2259namespace {
John McCall7f416cc2015-09-08 08:05:57 +00002260 /// Release a __block variable.
David Blaikie7e70d682015-08-18 22:40:54 +00002261 struct CallBlockRelease final : EHScopeStack::Cleanup {
John McCall73064872011-03-31 01:59:53 +00002262 llvm::Value *Addr;
2263 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
2264
Craig Topper4f12f102014-03-12 06:41:41 +00002265 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002266 // Should we be passing FIELD_IS_WEAK here?
John McCall73064872011-03-31 01:59:53 +00002267 CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
2268 }
2269 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00002270} // end anonymous namespace
John McCall73064872011-03-31 01:59:53 +00002271
2272/// Enter a cleanup to destroy a __block variable. Note that this
2273/// cleanup should be a no-op if the variable hasn't left the stack
2274/// yet; if a cleanup is required for the variable itself, that needs
2275/// to be done externally.
2276void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
2277 // We don't enter this cleanup if we're in pure-GC mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002278 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly)
John McCall73064872011-03-31 01:59:53 +00002279 return;
2280
John McCall7f416cc2015-09-08 08:05:57 +00002281 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup,
2282 emission.Addr.getPointer());
John McCall73064872011-03-31 01:59:53 +00002283}
John McCall7959fee2011-09-09 20:41:01 +00002284
2285/// Adjust the declaration of something from the blocks API.
2286static void configureBlocksRuntimeObject(CodeGenModule &CGM,
2287 llvm::Constant *C) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002288 if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
John McCall7959fee2011-09-09 20:41:01 +00002289
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002290 auto *GV = cast<llvm::GlobalValue>(C->stripPointerCasts());
Rafael Espindolac47b0a12014-05-08 13:07:37 +00002291 if (GV->isDeclaration() && GV->hasExternalLinkage())
John McCall7959fee2011-09-09 20:41:01 +00002292 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2293}
2294
2295llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2296 if (BlockObjectDispose)
2297 return BlockObjectDispose;
2298
2299 llvm::Type *args[] = { Int8PtrTy, Int32Ty };
2300 llvm::FunctionType *fty
2301 = llvm::FunctionType::get(VoidTy, args, false);
2302 BlockObjectDispose = CreateRuntimeFunction(fty, "_Block_object_dispose");
2303 configureBlocksRuntimeObject(*this, BlockObjectDispose);
2304 return BlockObjectDispose;
2305}
2306
2307llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2308 if (BlockObjectAssign)
2309 return BlockObjectAssign;
2310
2311 llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, Int32Ty };
2312 llvm::FunctionType *fty
2313 = llvm::FunctionType::get(VoidTy, args, false);
2314 BlockObjectAssign = CreateRuntimeFunction(fty, "_Block_object_assign");
2315 configureBlocksRuntimeObject(*this, BlockObjectAssign);
2316 return BlockObjectAssign;
2317}
2318
2319llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2320 if (NSConcreteGlobalBlock)
2321 return NSConcreteGlobalBlock;
2322
2323 NSConcreteGlobalBlock = GetOrCreateLLVMGlobal("_NSConcreteGlobalBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002324 Int8PtrTy->getPointerTo(),
2325 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002326 configureBlocksRuntimeObject(*this, NSConcreteGlobalBlock);
2327 return NSConcreteGlobalBlock;
2328}
2329
2330llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2331 if (NSConcreteStackBlock)
2332 return NSConcreteStackBlock;
2333
2334 NSConcreteStackBlock = GetOrCreateLLVMGlobal("_NSConcreteStackBlock",
Craig Topper8a13c412014-05-21 05:09:00 +00002335 Int8PtrTy->getPointerTo(),
2336 nullptr);
John McCall7959fee2011-09-09 20:41:01 +00002337 configureBlocksRuntimeObject(*this, NSConcreteStackBlock);
2338 return NSConcreteStackBlock;
2339}